前几天项目比较忙,今天继续学习
Swoole_webscoket_server
server端代码,测试的发现一个坑,可真的是坑死我了
//创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("0.0.0.0", 9502); $ws->set( [ 'enable_static_handler' => true, 'document_root' => "/data/www", ] ); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { $ws->push($request->fd, "hello, welcome\n"); }); //监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}"); }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); $ws->start();
client端代码
<html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>WS Client</h1> <script> var wsUrl = "ws://127.0.0.1:9502"; var ws = new WebSocket(wsUrl); ws.onopen = function (evt) { ws.send('hello swoole'); console.log('conected-success'); }; ws.onmessage = function (evt) { console.log('ws-server return' + evt.data); } ws.onclose = function (evt) { console.log('close'); } ws.onerror = function (evt,e) { console.log('error:' + e.error + '\n'); } </script> </body> </html>
碰到一个错误: WebSocket connection to 'ws://127.0.0.1:9502/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSE
这个错误是因为我在云服务器运行的 在本地电脑访问html文件,所以一直没办法建立正确链接webscoket,这里
var wsUrl = "ws://127.0.0.1:9502";要写成云服务器的IP才可以正确访问,还有记得端口要开放,还有防火墙设置