forked from matyhtf/webim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.php
268 lines (243 loc) · 6.93 KB
/
Server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
<?php
namespace WebIM;
use Swoole;
class Server extends Swoole\Protocol\CometServer
{
/**
* @var Store\File;
*/
protected $store;
protected $users;
const MESSAGE_MAX_LEN = 1024; //单条消息不得超过1K
const WORKER_HISTORY_ID = 0;
function __construct($config = array())
{
//将配置写入config.js
$config_js = <<<HTML
var webim = {
'server' : '{$config['server']['url']}'
}
HTML;
file_put_contents(WEBPATH . '/client/config.js', $config_js);
//检测日志目录是否存在
$log_dir = dirname($config['webim']['log_file']);
if (!is_dir($log_dir))
{
mkdir($log_dir, 0777, true);
}
if (!empty($config['webim']['log_file']))
{
$logger = new Swoole\Log\FileLog($config['webim']['log_file']);
}
else
{
$logger = new Swoole\Log\EchoLog;
}
$this->setLogger($logger); //Logger
/**
* 使用文件或redis存储聊天信息
*/
$this->setStore(new \WebIM\Store\File($config['webim']['data_dir']));
$this->origin = $config['server']['origin'];
parent::__construct($config);
}
function setStore($store)
{
$this->store = $store;
}
/**
* 下线时,通知所有人
*/
function onExit($client_id)
{
$userInfo = $this->store->getUser($client_id);
if ($userInfo)
{
$resMsg = array(
'cmd' => 'offline',
'fd' => $client_id,
'from' => 0,
'channal' => 0,
'data' => $userInfo['name'] . "下线了",
);
$this->store->logout($client_id);
//将下线消息发送给所有人
$this->broadcastJson($client_id, $resMsg);
}
$this->log("onOffline: " . $client_id);
}
function onTask($serv, $task_id, $from_id, $data)
{
$req = unserialize($data);
if ($req)
{
switch($req['cmd'])
{
case 'getHistory':
$history = array('cmd'=> 'getHistory', 'history' => $this->store->getHistory());
if ($this->isCometClient($req['fd']))
{
return $req['fd'].json_encode($history);
}
//WebSocket客户端可以task中直接发送
else
{
$this->sendJson($req['fd'], $history);
}
case 'addHistory':
$this->store->addHistory($req['fd'], $req['msg']);
break;
default:
break;
}
}
}
function onFinish($serv, $task_id, $data)
{
$this->send(substr($data, 0, 32), substr($data, 32));
}
/**
* 获取在线列表
*/
function cmd_getOnline($client_id, $msg)
{
$resMsg = array(
'cmd' => 'getOnline',
);
$users = $this->store->getOnlineUsers();
$info = $this->store->getUsers(array_slice($users, 0, 100));
$resMsg['users'] = $users;
$resMsg['list'] = $info;
$this->sendJson($client_id, $resMsg);
}
/**
* 获取历史聊天记录
*/
function cmd_getHistory($client_id, $msg)
{
$task['fd'] = $client_id;
$task['cmd'] = 'getHistory';
$task['offset'] = '0,100';
//在task worker中会直接发送给客户端
$this->getSwooleServer()->task(serialize($task), self::WORKER_HISTORY_ID);
}
/**
* 登录
* @param $client_id
* @param $msg
*/
function cmd_login($client_id, $msg)
{
$info['name'] = $msg['name'];
$info['avatar'] = $msg['avatar'];
//回复给登录用户
$resMsg = array(
'cmd' => 'login',
'fd' => $client_id,
'name' => $msg['name'],
'avatar' => $msg['avatar'],
);
//把会话存起来
$this->users[$client_id] = $resMsg;
$this->store->login($client_id, $resMsg);
$this->sendJson($client_id, $resMsg);
//广播给其它在线用户
$resMsg['cmd'] = 'newUser';
//将上线消息发送给所有人
$this->broadcastJson($client_id, $resMsg);
//用户登录消息
$loginMsg = array(
'cmd' => 'fromMsg',
'from' => 0,
'channal' => 0,
'data' => $msg['name'] . "上线了",
);
$this->broadcastJson($client_id, $loginMsg);
}
/**
* 发送信息请求
*/
function cmd_message($client_id, $msg)
{
$resMsg = $msg;
$resMsg['cmd'] = 'fromMsg';
if (strlen($msg['data']) > self::MESSAGE_MAX_LEN)
{
$this->sendErrorMessage($client_id, 102, 'message max length is '.self::MESSAGE_MAX_LEN);
return;
}
//表示群发
if ($msg['channal'] == 0)
{
$this->broadcastJson($client_id, $resMsg);
$this->getSwooleServer()->task(serialize(array(
'cmd' => 'addHistory',
'msg' => $msg,
'fd' => $client_id,
)), self::WORKER_HISTORY_ID);
}
//表示私聊
elseif ($msg['channal'] == 1)
{
$this->sendJson($msg['to'], $resMsg);
//$this->store->addHistory($client_id, $msg['data']);
//$this->sendJson($msg['from'], $resMsg);
}
}
/**
* 接收到消息时
* @see WSProtocol::onMessage()
*/
function onMessage($client_id, $ws)
{
$this->log("onMessage #$client_id: " . $ws['message']);
$msg = json_decode($ws['message'], true);
if (empty($msg['cmd']))
{
$this->sendErrorMessage($client_id, 101, "invalid command");
return;
}
$func = 'cmd_'.$msg['cmd'];
$this->$func($client_id, $msg);
}
/**
* 发送错误信息
* @param $client_id
* @param $code
* @param $msg
*/
function sendErrorMessage($client_id, $code, $msg)
{
$this->sendJson($client_id, array('cmd' => 'error', 'code' => $code, 'msg' => $msg));
}
/**
* 发送JSON数据
* @param $client_id
* @param $array
*/
function sendJson($client_id, $array)
{
$msg = json_encode($array);
$this->send($client_id, $msg);
}
/**
* 广播JSON数据
* @param $client_id
* @param $array
*/
function broadcastJson($sesion_id, $array)
{
$msg = json_encode($array);
$this->broadcast($sesion_id, $msg);
}
function broadcast($current_session_id, $msg)
{
foreach ($this->users as $client_id => $name)
{
if ($current_session_id != $client_id)
{
$this->send($client_id, $msg);
}
}
}
}