就喜欢这种简单几行代码就可以看效果的。
先说注意事项:
开启外网端口(阿里云、腾讯云等,还有用宝塔的也要哦)
IP是自己服务器的IP
这个一个简单的实例,不可以直接用于线上,长连接还需要心跳哒
自己看哈
php服务端(ws_server.php):
<?php error_reporting(E_ALL); //官网demo $server = new swoole_websocket_server("0.0.0.0", 9502); $server->on('open', function (swoole_websocket_server $server, $request) { echo "server: handshake success with fd{$request->fd}\n";//$request->fd 是客户端id }); $server->on('message', function (swoole_websocket_server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; $server->push($frame->fd, "您好{$frame->fd} ,this is server,您的数据是:".$frame->data);//$frame->fd 是客户端id,$frame->data是客户端发送的数据 //服务端向客户端发送数据是用 $server->push( '客户端id' , '内容') }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start();
然后运行服务端:
php ws_server.php #启动一下,观察实时状况
html端请求:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>test</title> <script type="text/javascript"> if ("WebSocket" in window) { // 打开一个 web socket var ws = new WebSocket("ws://ip:9502"); ws.onopen = function () { // Web Socket 已连接上,使用 send() 方法发送数据 ws.send("链接成功,第一次发送" ); }; ws.onmessage = function (evt) { var received_msg = evt.data; console.log('receive', evt.data) alert("数据已接收..." + evt.data); }; ws.onclose = function () { // 关闭 websocket alert("连接已关闭..."); }; } else { // 浏览器不支持 WebSocket alert("您的浏览器不支持 WebSocket!"); } function WebSocketTest() { var msg = window.prompt(); ws.send(msg) } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()">发送数据</a> </div> </body> </html>
监控结果:
[root@asdfasdf sw]# php ws_server.php server: handshake success with fd1 receive from 1:发送数据,opcode:1,fin:1 receive from 1:dsd,opcode:1,fin:1 receive from 1:aaaaa,opcode:1,fin:1 receive from 1:close,opcode:1,fin:1 receive from 1:..,opcode:1,fin:1
html控制台: