Because of the limited capacity of this article, there are many chat logic details are not implemented, only to achieve a mass, the specific code as follows:
PHP Code:
$serv = new Swoole_websocket_server ("127.0.0.1", 3999); Basic settings for the service $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 ' => 600,); $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 ~"); 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 ~";
Default: $send _msg= "said: {$data [' msg '] [' Speak ']}";
Break 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:
<!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Recommended article: PHP installation Swoole extension method using Swoole to extend the PHP WebSocket sample
The above code to share the Php+swoole to achieve a simple multiplayer online chat group of related code, I hope this article is helpful to everyone.