Swoole WebSocket服务器测试
作者:互联网
1.新建服务端ws.php
<?php //创建WebSocket Server对象,监听0.0.0.0:9502端口 $ws = new Swoole\WebSocket\Server('0.0.0.0', 8892); //监听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();
2.新建test.htm客户端测试
备注:ws://和wss://前缀分别表示WebSocket连接和安全的WebSocket连接。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Swoole-Web-Socker测试</title> </head> <body> <script> var wsServer = 'ws://124.220.192.59:8892'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); }; websocket.onerror = function (evt, e) { console.log('Error occured: ' + evt.data); }; </script> </body> </html>
标签:function,WebSocket,Swoole,data,ws,服务器,websocket,evt 来源: https://www.cnblogs.com/shineen/p/16414325.html