Due to the limited capacity of this article, there are a lot of chat logic details are not implemented, only the implementation of the bulk, the specific code is as follows:
PHP Code:
$serv = new Swoole_websocket_server ("127.0.0.1", 3999);//Service Basic Settings $serv->set (' worker_num ' = 2, ' Reactor_ Num ' =>8, ' task_worker_num ' =>1, ' dispatch_mode ' + 2, ' debug_mode ' = + 1, ' daemonize ' = = True, ' log_file ' = > __dir__. ' /log/webs_swoole.log ', ' heartbeat_check_interval ' =, ' heartbeat_idle_time ', ' = ', '); $serv->on (' Connect ', function ($serv, $FD) {//echo "client: $FD Connect.". Php_eol;}); /test Receive$serv->on ("Receive", Function (Swoole_server $serv, $FD, $from _id, $data) {//echo "receive#{$from _id}: Receive $data ". Php_eol;}); $serv->on (' Open ', function ($server, $req) {//echo "server#{$server->worker_pid}: Handshake success with fd#{$ REQ->FD} ". php_eol;;/ /echo Php_eol;}); $serv->on (' message ', function ($server, $frame) {//echo "message:". $frame->data. Php_eol, $msg =json_decode ($frame->data,true), switch ($msg [' type ']) {case ' login ': $server->push ($frame->fd , "Welcome welcome ~"); break;default:break;} $msg [' fd ']= $frame->fd; $server->task ($msg);}); $serv->on ("Workerstart", Function ($server, $workerid) {//echo "Workerstart:" $workerid. php_eol;//echo Php_eol;}); $serv->on ("task", "On_task"), $serv->on ("Finish", function ($serv, $task _id, $data) {return;}); $serv->on (' Close ', function ($server, $FD, $from _id) {//Echo ' connection close: ' $FD. php_eol;//echo Php_eol;}); $serv->start (); function On_task ($serv, $task _id, $from _id, $data) {switch ($data [' type ']) {case ' login ': $send _msg= " said: I came ~ "; Break;default: $send _msg=" said: {$data [' msg '] [' Speak ']} "; foreach ($serv->connections as $conn) {if ($conn! = $data [' fd ']) {if (Strpos ($data [' msg '] [' name '], "visitor") ===0) {$name =$ data[' msg ' [' Name ']. " _ ". $data [' fd '];} else{$name = $data [' msg '] [' name '];}} else{$name = "I";} $serv->push ($conn, $name. $send _msg);} return;} function On_finish ($serv, $task _id, $data) {return true;}
Front-End Code:
WebSocket testWebSocket Test
Nickname:Send
Recommended article: PHP installation Swoole extension method using Swoole extension PHP websocket example
The above code to share the Php+swoole implementation of simple multiplayer online chat mass of the relevant code, I hope this article is helpful to everyone.