-
Notifications
You must be signed in to change notification settings - Fork 0
/
webchat.php
43 lines (35 loc) · 1.2 KB
/
webchat.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
<?php
$server = new swoole_websocket_server('0.0.0.0', 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
echo "Server: Handshake success with fd{$request->fd}\n";
echo $server->connection_info;
});
function getRandomColor() {
$tmp = '0123456789abcdef';
$color = '#' . substr(str_shuffle($tmp), 0, 6);
return $color;
}
$server->on('message', function (swoole_websocket_server $server, $frame) {
echo "Receive from {$frame->fd}: {$frame->data}, opcode: {$frame->opcode}, fin: {$frame->finish}\n";
$res = json_decode($frame->data, TRUE);
$data = [
'uid' => $frame->fd,
'msg' => $res['msg'],
'nickname' => $res['nickname']
];
if (!isset($_SESSION['bgcolor'])) {
$_SESSION['bgcolor'] = getRandomColor();
}
$data['color'] = $_SESSION['bgcolor'];
$data = json_encode($data);
// $data = sprintf('%s SAY: %s', $frame->fd, $data);
// https://wiki.swoole.com/wiki/page/427.html
foreach ($server->connection_list() as $fd) {
$server->push($fd, $data);
}
});
$server->on('close', function ($ser, $fd) {
echo "Client {$fd} closed\n";
unset($_SESSION['bgcolor']);
});
$server->start();