1.swoole使用swoole_event_add()注册事件完成聊天室
客户端代码
<?php $socket = stream_socket_client("tcp://127.0.0.1:9501",$errno,$errstr,30); function onRead(){ global $socket; $buffer = stream_socket_recvfrom($socket,1024); if(!$buffer){ swoole_event_del($socket); } echo "REV{$buffer}".PHP_EOL; fwrite(STDOUT,"Enter MSG"); } function onWrite(){ global $socket; echo "ON write".PHP_EOL; } function onInput(){ global $socket; $msg = trim(fgets(STDIN)); if($msg == "exit"){ swoole_event_exit(); exit(); } swoole_event_write($socket,$msg); fwrite(STDOUT, "Enter Msg".PHP_EOL); } swoole_event_add($socket,'onRead','onWrite'); swoole_event_add(STDIN,"onInput"); ?>
2.服务端代码
<?php class Server{ private $serv; private $test; public function __construct(){ $this->serv = new swoole_server("0.0.0.0",'9501'); $this->serv->set([ 'worker_num'=>2, ]); $this->serv->on('Start',[$this,'onStart']); $this->serv->on('Connect',[$this,'onConnect']); $this->serv->on("Close",[$this,'onClose']); $this->serv->on('Receive',[$this,'onReceive']); $this->serv->start(); } public function onStart($serv){ echo "Start".PHP_EOL; } public function onConnect($serv,$fd,$from_id){ echo "Client connect".PHP_EOL; } public function onClose($serv,$fd,$from_id){ echo "Client close connections".PHP_EOL; } public function onReceive($serv,$fd,$from_id,$data){ echo "GET Message From Client".PHP_EOL; echo $data.PHP_EOL; foreach($serv->connections as $client){ if($fd != $client){ $serv->send($client,$data); } } } } $Server = new Server();