web端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket</title> </head> <body> <script> var wsServer = "ws://192.168.32.133:9501"; var ws = new WebSocket(wsServer); ws.onopen = function(evt){ console.log("链接成功"); } ws.onclose = function(evt){ console.log("关闭"); } ws.onmessage = function(evt){ console.log(evt.data); } ws.onerror = function(evt,e){ console.log('error'); } </script> </body> </html>
服务端代码:
<?php //创建websocket服务器 $ws = new swoole_websocket_server("0.0.0.0",9501); //on //open 建立链接 $ws 服务器,$request:客户端信息 $ws->on('open',function($ws,$request){ var_dump($request); $ws->push($request->fd,"welcome \n"); }); //message 接受信息 $ws->on('message',function($ws,$request){ echo "Message:".$request->data; $ws->push($request->fd,'get it message'); }); //close 关闭链接 $ws->on('close',function($ws,$request){ echo "关闭websocket连接\n"; }); $ws->start();