Swoole and WebSocket Simple chat room implementation method

Source: Internet
Author: User
Tags sessionstorage

First of all, I want to say some of the habits of code, first, any configurable parameters or variables are written to a config file. Second, the code must have a log record and perfect error and record the error. Anyway, swoole should be what every phper must know, and it claims to have redefined PHP. This chat room improves program performance by leveraging the Swoole high concurrency and asynchronous non-blocking features.

First, define a swoole_lock and swoole_websocket_server , and configure the parameters, details of the specific parameters can go to Swoole official website to view.


Public Function Start () {   $this->lock = new Swoole_lock (Swoole_mutex);     //Lock operation on file or array, synchronized   $this->server = new Swoole_websocket_server ($this->addr, $this->port);   //Swoole provides websocket Server   $this->server->set (      ' daemonize ' + 0,      ' worker_num ' = > 4,      ' task_worker_num ' +, '      max_request ' = +,      ' log_file ' and Root_path. ' Storage\\logs\\swoole.log '       //swoole log path, 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 service   $this->server->start ();}

When there is a client link, simply record the client's information.


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 a message, the information is processed.


Public Function OnMessage ($server, $frame) {$data = Json_decode ($frame->data); Switch ($data->type) {case ' init ': Case ' init ': $this->users[$frame->FD] = $data->mess  Age ,//record each link information, also do not try to print out to see, because you can only see their link information $message = ' welcome '. $data->message.          ' joined the chat room ';          $response = Array (' type ' = + 1,//1 for system messages, 2 for user chat ' message ' + $message);        Break          Case ' chat ': Case ' chat ': $message = $data->message; $response = Array (' type ' = + 2,//1 for system messages, 2 for user chat ' username ' + $this->users[$frame->f          D], ' message ' = $message);        Break      Default:return false;    }//give the information to task processing $this->server->task ($response); The Public Function Ontask ($server, $task _id, $from _id, $message) {//iterates over all the client links and pushes the message past. (If you try to->server->conne the $thisCtions print it out, then you will find that he is empty. But when we used foreach to loop, it really worked.      ) 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 disconnects, the client information is deleted synchronously, and the log is logged, using the lock mechanism.


Public Function OnClose ($server, $fd)    {      $username = $this->users[$fd];      Release the client, synchronize with the lock      $this->lock->lock ();      unset ($this->users[$fd]);      $this->lock->unlock ();      if ($username) {        $response = array (          ' type ' = + 1,  //1 for system messages, and 2 for user chat          ' message ' = + $username. ' Left the chat room '        );        $this->server->task ($response);      }      Write_log ($FD. ' Disconnected ');    }

Service end, the following is the client, very simple, just need to use WebSocket link ok!


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 retry later ');    };      Websocket.onopen = function (event) {if (!sessionstorage.getitem (' username ')) {setName (); }else {username = Sessionstorage.getitem (' username ') websocket.send (json.stringify ({' Message ': US      Ername, ' 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 messages: &lt      ;/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>&Lt;span class= "message" > ' + data.message + ' </span></li> ');    }    };    Websocket.onclose = function (event) {alert (' loose, server is off '); };
Related Article

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.