Php uses swoole to implement a simple multi-person online chat group and swoole online chat. Php uses swoole to implement a simple multi-person online chat group. many details of swoole's online chat logic are not implemented, but only mass chat is implemented. Php code: $ servnewswoole_webso php uses swoole to implement a simple group of online chat and swoole online chat
Many details of the chat logic are not implemented. only group sending is implemented.
Php code:
$ Serv = new swoole_websocket_server ("127.0.0.1", 3999); // Basic service settings $ serv-> 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;}); // Test receive $ se Rv-> 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 (); func Tion on_task ($ serv, $ task_id, $ from_id, $ data) {switch ($ data ['type']) {case 'login': $ send_msg = "said: I am coming ~ "; Break; default: $ send_msg =" Description: {$ data ['MSG '] ['speak']} "; break ;} foreach ($ serv-> connections as $ conn) {if ($ conn! = $ Data ['fd ']) {if (strpos ($ data ['MSG'] ['name'], "tourist") = 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 test