3 回答
TA贡献1856条经验 获得超11个赞
一.服务器端: 1. 编辑server.php文件内容如下: <?php $reqs=array(); //保持客户端的长连接在这个数组里 $serv = new swoole_websocket_server("192.168.2.115", 9502); //如下可以设置多端口监听 //$server = new swoole_websocket_server("0.0.0.0", 9501, SWOOLE_BASE); //$server->addlistener('0.0.0.0', 9502, SWOOLE_SOCK_UDP); //$server->set(['worker_num' => 4]); $serv->on('Open', function($server, $req) { global $reqs; $reqs[]=$req->fd; echo "connection open: ".$req->fd."\n"; var_dump(count($reqs));//输出长连接数 }); $serv->on('Message', function($server, $frame) { global $reqs; echo "message: ".$frame->data."\n"; foreach($reqs as $fd){ $server->push($fd, $frame->data); } }); $serv->on('Close', function($server, $fd) { echo "connection close: ".$fd."\n"; }); $serv->start();12345678910111213141516171819202122232425262728 2. 启动上面实现的websocket服务代码 [songaimin@localhost Tests]$/usr/bin/php server.php1 客户端-同事打开两个浏览器模拟多client: 3. 在浏览器console里运行: var wsl= 'ws://192.168.2.115:9502' ws = new WebSocket(wsl);//新建立一个连接 //如下指定事件处理 ws.onopen = function(){ws.send('Test!'); }; ws.onmessage = function(evt){console.log(evt.data);/*ws.close();*/}; ws.onclose = function(evt){console.log('WebSocketClosed!');}; ws.onerror = function(evt){console.log('WebSocketError!');}; 1234567 4. 在任意浏览器console里手动执行: ws.send(888); //看每个浏览器的内容console输出应该是一样的就实验在成功了 ws.close();//关闭连接
- 3 回答
- 0 关注
- 316 浏览
添加回答
举报