PHP代码文件名 chat.php
<?php //创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("0.0.0.0", 9502); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "hello, welcome "); }); //监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data} "; $ws->push($frame->fd, "server: {$frame->data}"); }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed "; }); $ws->start();
html代码chat.html
<!DOCTYPE html> <html> <head> <title>HTML5</title> <meta charset="utf-8" /> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> <script> $(function() { var socket; var readyState = ["connecting", "connected", "closing", "closed"]; /* 打开连接事件 */ $("button:eq(0)").click(function() { try { /* 连接 */ socket = new WebSocket("ws://192.168.1.121:9502"); /* 绑定事件 */ socket.onopen = function() { $("#msg").html("连接成功..."); }; socket.onmessage = function(e) { $("#msg").html($("#msg").html() + "<br />" + e.data); }; socket.onclose = function() { $("#msg").html($("#msg").html() + "<br />关闭连接..."); }; } catch(exception) { $("#msg").html($("#msg").html() + "<br />有错误发生"); } }); /* 发送数据事件 */ $("button:eq(1)").click(function() { /* 检查文本框是否为空 */ if($("#data").val() == "") { alert("请输入数据!"); return; } try { socket.send($("#data").val()); $("#msg").html($("#msg").html() + "<br />发送数据:" + $("#data").val()); } catch (exception) { $("#msg").html($("#msg").html() + "<br />发送数据出错"); } /* 清空文本框 */ $("#data").val(""); }); /* 断开连接 */ $("button:eq(2)").click(function() { socket.close(); }); }); </script> </head> <body> <h1>WebSocket示例</h1> <input type="text" id="data" /> <button>打开连接</button> <button>发送数据</button> <button>关闭连接</button> <p id="msg"></p> </body> </html>
执行php chat.php
浏览器打开http://192.168.1.121/chat.html完成