What is WebSocket?
WebSocket is a persistent protocol, which is relative to HTTP non-persistence. to give a simple example, The life cycle of http1.0 is defined by the request, that is, a request, a response, for HTTP, this time the client and server session to this end, and in http1.1, slightly improved, that is, the addition of keep-alive, that is, in a Multiple request requests and multiple response accept operations can be performed in an HTTP connection. However, in real-time communication, there is not much role, HTTP can only be initiated by the client request, the server can return information, that is, the server can not actively push information to the client, unable to meet the requirements of real-time communication. And websocket can be persistent connection, that is, the client only need to do a handshake, the success of the continuous data communication, it is worth noting that the websocket to achieve full-duplex communication between the client and server, That is, server-side data updates can be actively pushed to the client side.
The following figure illustrates the handshake portion of the WebSocket connection between the client and the server, which can be done very easily in node because the net module provided by node has already encapsulated the socket socket, and the developer uses only a few The interaction of the data without the establishment of the processing connection.
Client and server The session content of the handshake when the socket is established, that is, request and response
A, client to establish websocket when the information requested to the server side
Get/chat Http/1.1host:server.example.comupgrade:websocket//Tell the server is now sending the WebSocket protocol connection: upgradesec-websocket-key:x3jjhmbdl1ezlkh9gbhxdw==//is a value of Base64 encode, which is randomly generated by the browser, Used to verify that the server-side return data is WebSocket assistant Sec-websocket-protocol:chat, superchatsec-websocket-version:13origin:php.cn
b, after the server obtains the information requested by the client, the data is processed and returned according to the WebSocket protocol, where the Sec-websocket-key is encrypted, etc.
http/1.1 101 Switching Protocolsupgrade:websocket//is still fixed and tells the client that the WebSocket protocol is about to be upgraded, not mozillasocket, Lurnarsocket or shitsocketconnection:upgradesec-websocket-accept:hsmrc0smlyukagmm5oppg2hagwk=//This is confirmed by the server, And after the encrypted sec-websocket-key, that is, the client requires the establishment of WebSocket authentication credentials Sec-websocket-protocol:chat
The process of creating a socket in PHP is explained
1, in PHP, the client and the server to establish a socket communication, first in PHP to create a socket and listen to the port information, the code is as follows:
<?php//the corresponding IP and port to create socket operation function WebSocket ($address, $port) {$server = Socket_create (Af_inet, Sock_stream, SOL _TCP); Socket_set_option ($server, Sol_socket, SO_REUSEADDR, 1);//1 accepts all packets Socket_bind ($server, $address, $port); Socket_listen ($server); return $server;}? >
2, design a loop to suspend the WebSocket channel for data reception, processing and transmission
<?php//listens to the created socket loop, processes the data function run () {//cycles until the socket disconnects while (true) {$changes = $this->sockets; $write =null; $except =null; /*//This function is the key to accept multiple connections at the same time, I understand it in order to block the program to continue to execute. Socket_select ($sockets, $write = null, $except = NULL, NULL); $sockets can be understood as an array in which the file descriptor is stored. When it changes (that is, there is a new message to or a client connected/disconnected), the Socket_select function returns and continues to execute. $write is listening for client write data, passing in NULL is not concerned whether there is a write change. $except is the element to be excluded from the $sockets, and passing in null is "listening" all. The last parameter is the time-out if 0: ends immediately if it is n>1: it ends at most n seconds, or if there is a new dynamic in a connection, returns if NULL: if there is a new dynamic in a connection, return */Socket_select ($ Changes, $write, $except, NULL); foreach ($changes as $sock) {//If a new client connection comes in, the if ($sock = = $this->master) {//accepts a socket connection $clien T=socket_accept ($this->master); A unique ID $key =uniqid () to the new connection incoming socket; $this->sockets[]= $client; Store the newly connected socket in the connection pool $this->users[$key]=array (' socket ' = $client,//record The new connection in the client socket information ' Shou ' =>false//flag the socketThe resource does not complete the handshake); Otherwise 1. Disconnect the socket for the client, 2.client send the message}else{$len = 0; $buffer = "; Read the information of the socket, note: The second parameter is to receive data as a reference, the third parameter is the length of the received data do{$l =socket_recv ($sock, $buf, 1000,0); $len + = $l; $buffer. = $buf; }while ($l ==1000); According to the socket in the user pool to find the corresponding $k, that is, the health id $k = $this->search ($sock); If the received message length is less than 7, the client's socket is disconnected if ($len <7) {//Disconnects the client's socket and $this->sockets and $this->u Sers inside to delete $this->send2 ($k); Continue }//Determine if the socket has been shook hands if (! $this->users[$k [' Shou ']) {//If there is no handshake, the handshake is handled $this->woshou ($k , $buffer); }else{//Go here is the client sent the message, the received information to Uncode processing $buffer = $this->uncode ($buffer, $k); if ($buffer ==false) {continue; }//If not empty, the message push operation $this->send ($k, $buffer); }}}}}?>
3, the above server-side completion of the pre-websocket work, waiting for the client connection, the client created WebSocket is very simple, the code is as follows:
var ws = new WebSocket ("WS://IP: Port");//Handshake listener Function ws.onopen=function () { ////status is 1 proof handshake succeeded, then send client custom name past if ( So.readystate==1) { //handshake successfully sent information to the server so.send (' type=add&ming= ' +n);} } Error return information function Ws.onerror = function () { console.log ("error");};/ /listen for server-side push messages ws.onmessage = function (msg) { console.log (msg);} Disconnect WebSocket Connection ws.onclose = function () { ws = FALSE;}
"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