PHP websocket Implement web chat room

Source: Internet
Author: User
Tags bitwise cdata chr ord php server php websocket

I. INTRODUCTION

HTTP requests can only be initiated by the client, the server response mode, the server is unable to proactively push data to the client, websocket the appearance of the perfect solution to this problem.
WebSocket and HTTP on the same level, are based on the TCP protocol, the client and the server use WebSocket communication need to handshake and transfer data two steps,
Handshake with HTTP status Code 101 Switch protocol from the HTTP protocol to the WebSocket protocol, after which it has nothing to do with the HTTP protocol.

Two. Handshake

WebSocket first initiated an HTTP request by the browser, the main request header content is as follows:
Connection: Informs the server that the current request connection is upgraded
Upgrade:websocket Upgrade tells the server that this HTTP link is an upgraded WebSocket link
SEC-WEBSOCKET-VERSION:13 Protocol version
sec-websocket-key:iyiyjdxldghybp4temonsq== Verify Key


The server response header is as follows
http/1.1 101 Switching Protocols Express Transformation Protocol
Upgrade:websocket
The Connection:upgrade server returns a notification that the client agrees to use the upgrade and uses the WebSocket protocol to refine the HTTP upgrade response
The sec-websocket-accept:ev/nt3aipwh9deafyympbbwkqwo= client Sec-websocket-key the encrypted string algorithm Base64_encode (SHA1 ( Sec-websocket-key + 258eafa5-e914-47da-95ca-c5ab0dc85b11));

Three. Data frame construction and parsing
  0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-------+-+-------------+-------------------------------+ | F| r| r| r| opcode| m|    Payload Len | Extended Payload Length | | i| s| s|  s| (4) |     a|             (7) | (16/64) | | n| v| v|       v| |             s|   |       (if payload len==126/127) | | |1|2|3| |             k|                               | |     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len = = 127 |                               + - - - - - - - - - - - - - - - +-------------------------------+ | | Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ |          Masking-key (continued) | Payload Data |                +-----------------------------------------------+: Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data Continued ... | +---------------------------------------------------------------+

Algorithm for constructing protocol text frame (PHP)

Where opcode for 1 represents a text frame

Private functionEncode$data){    $len=strlen($data); $encode= ' '; if($len< 126){        $encode=CHR(0X81).CHR($len) .$data; }Else if($len>= 126 &&$len<= 65535){        $low=$len& 0x00FF; $high= ($len& 0xff00) >> 8; $encode=CHR(0X81).CHR(0x7F).CHR($high) .CHR($low) .$data; }Else{encode=CHR(0X81).     }    return $encode;}

If Playload Len < 126, then Playloadlen is the true length of the data
If Playload len = 126, the length of the data is equal to Playload len, the unsigned integer corresponding to the 2 bytes is the true length of the data
If Playload len = 127, the length of the data is equal to Playload len, the unsigned integer corresponding to the 8 bytes is the true length of the data

I'm not familiar with bit arithmetic before, so here's a detailed procedure for building a data frame.
PHP uses CHR to convert data to a single character specified by standard ASCII
Length < 126 FIN + RSV1 + RSV2 + RSV3 + opcode = 0x81 = 10000001, plus data length and data
Length >=126 <= 65535 FIN + RSV1 + RSV2 + RSV3 + opcode = 0x81 = 10000001 plus Payload len = 0x7E = 126 Because the ASCII range is 0-127 or 1 Byte, the 2 bytes must be split into a single byte, high $high and low $low to represent
$low = $len & (11111111 = 0x00FF) The value of the second byte of $len is obtained. Because $len is two bytes, take the first byte value $len & (1111111100000000 = 0xff00) and move 8 bits to the right

An algorithm for parsing text frames

Private functionDecode$data){    if(!$data)return Array(); //the first byte and the 00001111 bitwise-and-op 4-bit data are opcode    $opcode=Ord(substr($data, 0, 1)) & 0x0f; //The second byte and 10000000 bitwise AND operation, retain the value of the first bit, then move right 7 bit to get the Ismask    $ismask= (Ord(substr($data, 1, 1)) & 0x80) >> 7; //the second byte and 01000000 bitwise-and-op-7-bit values are Playloadlen    $playloadlen=Ord(substr($data, 1, 1)) & 0x7f; $cdata=$maskkey=$decode= ' '; if($playloadlen< 126){        $maskkey=substr($data, 2, 4); $cdata=substr($data, 6); }Else if($playloadlen= = 126){        $maskkey=substr($data, 4, 4); $cdata=substr($data, 8); }Else if($playloadlen= = 127){        $maskkey=substr($data, 10, 4); $cdata=substr($data, 14); }    if($cdata&&$maskkey){         for($i= 0;$i<strlen($cdata);$i++){            $decode{$i} =$cdata{$i} ^$maskkey[$i% 4]; }        $decode=Join(‘‘,$decode); }    return Array($opcode,$ismask,$decode);}

WEBSOCKET specifies that the data sent to the server by the client must be masked, and the data sent to the client by the servers is not masked.
Decoding algorithm: Playload the original data of each word Poute and 4 modulo, and then the original character and the corresponding position after the previous mask character to be different or operation can be
Data[i] = Source[i] ^ Maskkey[i/4];

Four. PHP Server

The previous Select method for the socket is not well understood,

function Socket_select (array & $read, array & $write, array & $except, $tv _sec, [, int $tv _usec = 0])

1. When the new connection arrives, the port being monitored is active, and if the new data arrives or the client closes the link, the corresponding client socket is active instead of the port being monitored on the server.
2. If the client sends data that is not read, Socket_select will always show that the client is active and save it in the read array
3. If the client first shuts down, you must manually shut down the corresponding client socket on the server, otherwise socket_select will always show that the client is active (this is the same as "there is a new connection coming and then it is not used socket_access to read it out, The port that caused the listener to remain active "is the same)

$read is a reference variable, each time we execute, we need to listen to the socket resource, after execution, return to the active socket resource, the core pseudo-code is as follows


$socket = Socketcreate ();
$socket _select = Array ($socket);
while (true) {
$read = $socket _select;
Socket_select ($read, $write, $except, NULL);
foreach ($read as $sock) {
if ($sock = = $socket) {//When new connection arrives

}else{//when the client sends data or the client shuts down

}
}
}

Five. Client

The client WebSocket API is very simple.

//Create a WebSocket connectionvarWS =NewWebSocket ("Ws:xxxxx");//WebSocket Creating a success EventWs.onopen =function () {};//websocket Receive Message EventsWs.onmessage =function(e) {varmsg =Json.parse (e.data);}//WebSocket Error EventsWs.onerror =function () {};//websocket shutdown EventsWs.close =function () {};

Full code on my GitHub

Reference articles

Http://www.cnblogs.com/zhenbianshu/p/6111257.html

Http://blog.csdn.net/u010487568/article/details/20908427?utm_source=tuicool&utm_medium=referral

PHP websocket Implement web chat room

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.