<?php //创建webSocket服务器 $serv=new swoole_websocket_server('0.0.0.0',9501); //获取请求 //on //open 建立连接 $serv:服务器 $request:客户端信息 $serv->on('open',function($serv,$request){ var_dump($request); $serv->push($request->fd,"welcome "); }); //message 接收信息 $serv->on('message',function($serv,$request){ echo "Message:$request->data"; $serv->push($request->fd,"get it message"); }); //close 关闭连接 $serv->on('close',function($serv,$request){ echo "close "; }); //启动服务器 $serv->start(); //php index.php //ps -ajft //service iptables stop //关闭防火墙 ?>
<!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8"> <title></title> </head> <body> <script> var wsServer="ws://192.168.10.31:9501"; 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('error'); } </script> </body> </html>