说明
需要安装 swoole扩展

在linux系统下通过命令行执行php文件。(win下没有swoole扩展)
示例代码
1. 前端websocket
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
| <html> <head> <meta charset="UTF-8"> <title>Web sockets test</title> <script type="text/javascript"> var ws; function ToggleConnectionClicked() { if( typeof(ws) != 'undefined' && ws.readyState == 1 ) { alert('已连接服务器,请勿重复连接!'); return false; }
try { ws = new WebSocket("ws://192.168.198.221:9501");//连接服务器,改成你服务器地址 ws.onopen = function(event){ alert("已经与服务器建立了连接\r\n当前连接状态:"+this.readyState); }; ws.onmessage = function(event){ // alert("接收到服务器发送的数据:\r\n"+event.data); var chat_content = document.getElementById("chat_content"); chat_content.innerHTML = chat_content.innerHTML+event.data+"<br />"; // console.log(event.data); }; ws.onclose = function(event){ alert("已经与服务器断开连接\r\n当前连接状态:"+this.readyState); }; ws.onerror = function(event){ alert("WebSocket异常!"); }; } catch (ex) { alert(ex.message); } }; function SendData() { try{ var content = document.getElementById("content").value; if(content){ ws.send(content); } }catch(ex){ alert(ex.message); } }; function seestate(){ if( typeof(ws) == 'undefined' ) { alert('还未连接服务器!'); return false; } alert(ws.readyState); };
function ClearChatContent(){ document.getElementById("chat_content").innerHTML = ""; }; </script> </head> <body> <button id='ToggleConnection' type="button" onclick='ToggleConnectionClicked();'>连接服务器</button><br /><br /> <textarea id="content" ></textarea> <button id='ToggleConnection' type="button" onclick='SendData();'>发送</button><br /><br /> <button id='ToggleConnection' type="button" onclick='seestate();'>查看状态</button><br /><br /> <button type="button" onclick='ClearChatContent();'>清屏</button><br /><br /> <div id="chat_content"></div> </body> </html>
|
2. 后台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
| <?php # 创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("0.0.0.0", 9501); # 监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { // var_dump($request->fd, $request->get, $request->server); echo $request->server['remote_addr']."已连接\n"; $ws->push($request->fd, "hello, welcome.your ip is {$request->server['remote_addr']}\n"); # 广播 foreach($ws->connections as $fd) { $ws->push($fd, "用户{$request->fd}已登录聊天"); } }); # 监听WebSocket消息事件 $ws->on('message', function (swoole_websocket_server $server, $frame) { echo $frame->fd." Message: {$frame->data}\n"; # 广播 foreach($server->connections as $fd) { $server->push($fd, "用户{$frame->fd}说: {$frame->data}"); } }); # 监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { # var_dump($ws, $fd); echo "client-{$fd} is closed\n"; }); $ws->start();
|
3. 通过命令行进行启动php
1
| ./php /www/wwwroot/a/testa.php
|
4.测试
分别通过两个不同的浏览器打开前端H5页面(本人使用火狐浏览器和360浏览器),并连接服务器
火狐浏览器

360浏览器

发送信息

后台显示
