<?php //创建webSocket服务器 $ws=new swoole_websocket_server('0.0.0.0',9502); //open $ws->on('open',function($ws,$request){ echo "新用户 $request->fd 加入 \n"; //设置用户ID $GLOBALS['fd'][$request->fd]['id']=$request->fd; //设置用户名 $GLOBALS['fd'][$request->fd]['name']='匿名用户'; }); //message $ws->on('message',function($ws,$request){ $msg=$GLOBALS['fd'][$request->fd]['name'].":".$request->data."\n"; //用户设置昵称 if(strstr($request->data,"#name#")){ $GLOBALS['fd'][$request->fd]['name']=str_replace("#name#",'',$request->data); }else{ //用户信息发送 //发送到每一个客户端 foreach($GLOBALS['fd'] as $i){ $ws->push($i['id'],$msg); } } }); //close $ws->on('close',function($ws,$request){ echo "客户端--{$request}断开连接\n"; //清除连接池 unset($GLOBALS['fd'][$request]); }); //启动服务器 $ws->start(); //php index.php //ps -ajft //查看启动进程 //service iptables stop //关闭防火墙
?>