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
| <?php
//创建WebSocket Server对象,监听0.0.0.0:9502端口,这个ip得注意一下,很多新手不懂这个0.0.0.0,跟你直接绑定127.0.0.1,的区别,如果你直接写127.0.0.1的话,你用内网ip访问本机地址是访问不到的,0.0.0.0,是不限制ip,127.0.0.1,是限制只能用127.0.0.1来访问注意这一点 $ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
//监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) {
//把自己的id返回回去 $redata = [ 'fd'=>$request->fd ];
$ws->push($request->fd,json_encode($redata)); });
//监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { //解析json $data = json_decode($frame->data,true); //拼接要发送的数据 $redata = [ 'wfid'=>$frame->fd, 'conent'=>$data['conent'] ]; //发送 $ws->push($data['fid'],json_encode($redata)); });
//监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "{$fd} 关闭连接"; });
$ws->start();
|