该 websocket 简单例子基于 php swoole 扩展详细介绍见swoole 官网,编译安装这里不多说了。
前端 websocket
<html> <head> <meta charset="UTF-8"> <title>Web sockets test</title> <script> var ws; function ToggleConnectionClicked() { if( typeof(ws) != 'undefined' && ws.readyState == 1 ) { alert('已连接服务器,请勿重复连接!'); return false; } try { ws = new WebSocket("ws://192.168.5.112: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); } </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 /> <div id="chat_content"></div> </body> </html>
后端 php
<?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();
后端 php 代码需要在 CLI 即在命令行中运行
测试截图:
只打开火狐:
打开 IE:
终端中: