PHP+swoole实现简单多人在线聊天群发

前端之家收集整理的这篇文章主要介绍了PHP+swoole实现简单多人在线聊天群发前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

由于本文的能力有限,有好多聊天逻辑的细节没有实现,只实现了群发,具体代码如下所示:

PHP代码

set(array( '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' => 60,'heartbeat_idle_time' => 600,)); $serv->on('connect',function ($serv,$fd){ // echo "client:$fd Connect.".PHP_EOL; }); //测试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',$frame) { // echo "message: ".$frame->data.PHP_EOL; $msg=json_decode($frame->data,true); switch ($msg['type']){ case 'login': $server->push($frame->fd,"欢迎欢迎~"); break; default: break; } $msg['fd']=$frame->fd; $server->task($msg); }); $serv->on("workerstart",$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',$from_id) { // echo "connection close: ".$fd.PHP_EOL; // echo PHP_EOL; }); $serv->start(); function on_task($serv,$data) { switch ($data['type']){ case 'login': $send_msg="说:我来了~"; break; default: $send_msg="说:{$data['msg']['speak']}"; break; } foreach ($serv->connections as $conn){ if ($conn!=$data['fd']){ if (strpos($data['msg']['name'],"游客")===0){ $name=$data['msg']['name']."_".$data['fd']; }else{ $name=$data['msg']['name']; } }else{ $name="我"; } $serv->push($conn,$name.$send_msg); } return; } function on_finish($serv,$data){ return true; }

前端代码

PHP;"> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> WebSocket测试

推荐文章

以上代码给大家分享PHP+swoole实现简单多人在线聊天群发的相关代码,希望本文所述对大家有所帮助。

原文链接:https://www.f2er.com/php/20489.html

猜你在找的PHP相关文章