How to create a simple chat room using PHP websocket

Source: Internet
Author: User
Tags php programming php websocket
Socketis the intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol. The previous chapters we talked about the difference between the socket and HTTP, to understand the socket must first understand the difference between HTTP and TCP, simply said is a short chain, one is long chain, one is to go to the server pull data, one is the server can actively push data. HTTP connections are divided into short connections and long connections. Short connections can generally be implemented with Ajax, and long connections are websocket. Short connections are relatively simple to implement, but they are too resource-intensive. WebSocket efficient but compatible there are points of issue. WebSocket is the resource of HTML5.

PHP WebSocket Create a simple chat room process Introduction

PHP chat room used to be done by Ajax and PHP to achieve, today we will look at a PHP chat room websocket Technical practical examples.

1. Foreground client

Foreground file How to send information to the background server, and later research found to be using JS WebSocket technology, the following is commonly used JS WebSocket commonly used operations:

The code is as follows:

var socket = new WebSocket (' ws://localhost:8080 ');         Open socket         Socket.onopen = function (event) {         }        //Send an initialization message         socket.send (' I am the client and I\ ' m listen Ing! ');         Listener message         socket.onmessage = function (event) {             Console.log (' Client received a message ', event);           };  phpfensi.com        //monitor socket off          socket.onclose = function (event) {             Console.log (' Client notified socket Has closed ', event);           };           Close the socket ....         Socket.close ()        socket.onerror = function (evt) {console.log ("websocketerror!");};

Note: The first line sends a handshake request to the specified server, and if the server returns a legitimate HTTP header, the handshake succeeds, and then the message sent by the server is processed by listening for the OnMessage event. There are many other events to listen to, see the previous URL.

2. Backend Server

The process that the service side does is basically:

A. Suspending a socket socket process waiting for a connection

B. Traversing the socket array after having a socket connection

C. Handshake operation without handshake, receive data parsing and write buffer to output if handshake is already in progress

The sample code is as follows:

Public Function Start_server () {$this->socket = socket_create (Af_inet, Sock_stream, sol_tcp);  Allows use of local address socket_set_option ($this->socket, Sol_socket, SO_REUSEADDR, TRUE);  Socket_bind ($this->socket, $this->host, $this->port);  Up to 10 people connected, exceeding the client connection will return wsaeconnrefused error Socket_listen ($this->socket, $this->maxuser);    while (TRUE) {$this->cycle = $this->accept;    $this->cycle[] = $this->socket;    Blocking, Socket_select ($this->cycle, $write, $except, NULL) when there is a new connection; foreach ($this->cycle as $k = + $v) {if ($v = = = $this->socket) {if ($accept = socket_accept ($v)) &lt ;        0) {continue;        }//If the request is from the listener port that socket, a new socket is created for communication $this->add_accept ($accept);      Continue      } $index = Array_search ($v, $this->accept);      if ($index = = = NULL) {continue;        }//The socket with no message skips the IF (! @socket_recv ($v, $data, 1024x768, 0) | |! $data) {$this->close ($v);     Continue } if (! $this->ishand[$index]) {$this->upgrade ($v, $data, $index);        if (!empty ($this->function[' Add ')) {Call_user_func_array ($this->function[' add '), Array ($this));      } continue;      } $data = $this->decode ($data); if (!empty ($this->function[' send ')) {Call_user_func_array ($this->function[' send '], array ($data, $index, $thi      s));  }} sleep (1);  }}//Add a user for initial connection public function add_accept ($accept) {$this->accept[] = $accept;  $index = Array_keys ($this->accept);  $index = End ($index); $this->ishand[$index] = FALSE;}  Close a connection public function close ($accept) {$index = Array_search ($accept, $this->accept);  Socket_close ($accept);  unset ($this->accept[$index]);  unset ($this->ishand[$index]);  if (!empty ($this->function[' close ')) {Call_user_func_array ($this->function[' close '), Array ($this)); }}//Response Upgrade Protocol Public function upgrade ($accept, $data, $index) {if (Preg_match ("/sec-websockEt-key: (. *) \r\n/", $data, $match)) {$key = Base64_encode (SHA1 ($match [1].    ' 258eafa5-e914-47da-95ca-c5ab0dc85b11 ', true));      $upgrade = "http/1.1 101 switching protocol\r\n".      "Upgrade:websocket\r\n".      "Connection:upgrade\r\n". "Sec-websocket-accept:". $key.  "\r\n\r\n";    Must end with two carriage returns Socket_write ($accept, $upgrade, strlen ($upgrade));  $this->ishand[$index] = TRUE; }}

Description: There are a few key places, one is while (true) hangs the process, or executes once the process exits. The second is the use of socket_select and socket_accept functions. The third is the handshake when the client first requests it.

The following process is clear, when a new client request arrives, create a resource with socket_accept and join the $this->accept connection pool. and set its flag Ishand to false, then the next loop (because $this->cycle[] = $this->socket; $this->cycle changes, so Socket_select will return) The upgrade handshake is performed. Then wait for its new message to be ready.

"Related tutorials Recommended"

1. "Php.cn lonely Nine Cheap (4)-php video Tutorial"

2. PHP programming from getting started to mastering the full set of tutorials

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.