<?php$server=newswoole_websocket_server('0.0.0.0',9502);//创建swoole的websocket实例其中0.0.0.0代表监听所有回路包括127.0.0.1和192.168...
<?php $server = new swoole_websocket_server('0.0.0.0', 9502);// 创建swoole的websocket实例 其中 0.0.0.0 代表监听所有回路 包括127.0.0.1 和 192.168.*.* 和 外部IP, 端口是9502 //监听打开事件 $server->on('open', function ($server, $request){ var_dump($request->fd, $request->get, $request->server); $server->push($request->fd, "我是open\n"); }); //监听消息事件 $server->on('message', function ($server, $message){ echo "Message: {$message->data}\n"; $server->push($message->fd, "服务器给的: {$message->data}"); }); //监听关闭事件 $server->on('close', function ($server, $fd){ echo "客户端: {$fd} 关闭了"; }); $server->start();
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> <script> var wsServer = 'ws://192.168.33.10:9502'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("连接到服务器"); }; websocket.onclose = function (evt) { console.log("连接关闭"); }; websocket.onmessage = function (evt) { console.log('收到服务器信息' + evt.data); }; websocket.onerror = function (evt, e) { console.log('错误信息: ' + evt.data); }; </script> </html>
全文详见:http://xpxw.com/?id=61