Use swoole and websocket to develop simple chat rooms and swoolewebsocket

Source: Internet
Author: User
Tags sessionstorage

Use swoole and websocket to develop simple chat rooms and swoolewebsocket

First, I want to talk about some habits of writing code. First, any configurable parameters or variables must be written into a config file. Second, the Code must have a log record and complete error reporting and record the error. To put it bluntly, swoole should be something that every phper needs to understand. It claims to have redefined php. This chat room uses the features of swoole high concurrency and asynchronous non-blocking to improve program performance.

First, define a swoole_lock and swoole_websocket_server, and configure the parameters. For details about the parameters, go to the swoole official website.

Public function start ()
{$ This-> lock = new swoole_lock (SWOOLE_MUTEX); // lock files or arrays, synchronization has reached $ this-> server = new swoole_websocket_server ($ this-> addr, $ this-> port ); // Websocket Server $ this-> server-> set (array ('daemonize '=> 0, 'worker _ num' => 4, 'Task _ worker_num '=> 10, 'max _ request' => 1000, 'Log _ file' => ROOT_PATH. 'Storage \ logs \ swoole. log' // swoole log Path, which must be an absolute path); $ this-> server-> on ('open', array ($ this, 'onopen ')); $ this-> server-> on ('message', array ($ this, 'onmessage'); $ this-> server-> on ('task ', array ($ this, 'ontask'); $ this-> server-> on ('finish ', array ($ this, 'onfinish ')); $ this-> server-> on ('close', array ($ this, 'onclose '));
// Start the service $ this-> server-> start ();}

When there is a client link, the client information is simply recorded.

        public function onOpen($server, $request)        {            $message = array(                'remote_addr' => $request->server['remote_addr'],                'request_time' => date('Y-m-d H:i:s', $request->server['request_time'])            );            write_log($message);        }

When a client sends information, it processes the information.

Public function onMessage ($ server, $ frame) {$ data = json_decode ($ frame-> data); switch ($ data-> type) {case 'init ': case 'init': $ this-> users [$ frame-> fd] = $ data-> message; // record the information of each link. Do not print it out, because you can only see your own link information $ message = 'Welcome '. $ data-> message. 'added to the chatroom'; $ response = array ('type' => 1, // 1 indicates the system message, 2 indicates the user's chat 'message' => $ message); break; case 'chat': $ message = $ data-> message; $ response = array ('type' => 2, // 1 indicates the system message, 2 stands for user chat 'username' =>$ this-> users [$ frame-> fd], 'message' =>$ message); break; default: return false ;}
// Submit the information to the task for processing $ this-> server-> task ($ response);} public function onTask ($ server, $ task_id, $ from_id, $ message ){
// Iterate all client links to push messages. (If you try to print out $ this-> server-> connections, you will find it empty. But it was useful when we used foreach to go through the loop .) Foreach ($ this-> server-> connections as $ fd) {$ this-> server-> push ($ fd, json_encode ($ message ));} $ server-> finish ('task '. $ task_id. 'finished '. PHP_EOL );}

Finally, when the client is disconnected, the lock mechanism is used to synchronously Delete client information and record logs.

Public function onClose ($ server, $ fd) {$ username = $ this-> users [$ fd]; // release the client, use the lock to synchronize $ this-> lock (); unset ($ this-> users [$ fd]); $ this-> lock-> unlock (); if ($ username) {$ response = array ('type' => 1, // 1 indicates the system message, 2 indicates the user chats with 'message' => $ username. 'left the chatroom'); $ this-> server-> task ($ response);} write_log ($ fd. 'disconnected ');}

The server is finished. The following is the client. It is very simple. You only need to use the websocket link!

// Websocket let address = 'ws: // <? Php echo CLIENT_CONNECT_ADDR. ':'. CLIENT_CONNECT_PORT?> '; Let webSocket = new WebSocket (address); webSocket. onerror = function (event) {alert ('server connection error, please try again later ') ;}; webSocket. onopen = function (event) {if (! SessionStorage. getItem ('username') {setName ();} else {username = sessionStorage. getItem ('username') webSocket. send (JSON. stringify ({'message': username, 'type': 'init'}) ;}}; webSocket. onmessage = function (event) {console. log (event); let data = JSON. parse (event. data); if (data. type = 1) {$ (# chat-list2 '). append ('<li class = "ui-border-tb"> <span class = "username"> system message: </span> <span class = "message"> '+ data. message + '</span> </li>');} else if (data. type = 2) {$ (# chat-list2 '). append ('<li class = "ui-border-tb"> <span class = "username">' + data. username + ': </span> <span class = "message">' + data. message + '</span> </li>') ;}}; webSocket. onclose = function (event) {alert ('scatter, all servers are turned off ');};

For detailed code, go to my github to download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.