Home Backend Development PHP Tutorial Detailed explanation of php using websocket example_PHP tutorial

Detailed explanation of php using websocket example_PHP tutorial

Jul 13, 2016 am 10:36 AM
php websocket

Below I drew a picture to demonstrate the handshake part when establishing a websocket connection between client and server. This part can be completed very easily in node, because the net module provided by node has already encapsulated the socket. When developers use it, they only need to consider the interaction of data and do not need to deal with the establishment of connections. However, PHP does not. From socket connection, establishment, binding, monitoring, etc., we need to operate these by ourselves, so it is necessary to take it out and talk about it.

Detailed explanation of php using websocket example_PHP tutorial

① and ② are actually an HTTP request and response, but what we get during the processing is an unparsed string. Such as:

Copy code The code is as follows:

GET /chat HTTP/1.1
Host: server.example.com
Origin: http://www.jb51.com

The request we usually see looks like this. When this thing reaches the server, we can get this information directly through some code libraries.

1. Processing websocket in php

WebSocket connection is actively initiated by the client, so everything must start from the client. The first step is to parse the Sec-WebSocket-Key string sent by the client.

Copy code The code is as follows:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://www.jb51.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

Format of client request

First, php establishes a socket connection and listens for port information.

1. Establishment of socket connection

Regarding the establishment of sockets, I believe many people who have studied computer network in college know this. The following is a picture of the process of establishing a connection:

Copy code The code is as follows:

// Create a socket
$master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($master, $address, $port);
socket_listen($master);

Compared with node, the processing of this place is really troublesome. The above lines of code do not establish a connection, but these codes are what must be written to establish a socket. Since the processing process is slightly complicated, I wrote various processes into a class to facilitate management and calling.

Copy code The code is as follows:

//demo.php
Class WS {
    var $master;  // 连接 server 的 client
    var $sockets = array(); // 不同状态的 socket 管理
    var $handshake = false; // 判断是否握手

    function __construct($address, $port){
        // 建立一个 socket 套接字
        $this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)  
            or die("socket_create() failed");
        socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1) 
            or die("socket_option() failed");
        socket_bind($this->master, $address, $port)                   
            or die("socket_bind() failed");
        socket_listen($this->master, 2)                              
            or die("socket_listen() failed");

        $this->sockets[] = $this->master;

        // debug
        echo("Master socket  : ".$this->master."\n");

        while(true) {
            //自动选择来消息的 socket 如果是握手 自动选择主机
            $write = NULL;
            $except = NULL;
            socket_select($this->sockets, $write, $except, NULL);

            foreach ($this->sockets as $socket) {
                //连接主机的 client
                if ($socket == $this->master){
                    $client = socket_accept($this->master);
                    if ($client < 0) {
                        // debug
                        echo "socket_accept() failed";
                        continue;
                    } else {
                        //connect($client);
                        array_push($this->sockets, $client);
                        echo "connect clientn";
                    }
                } else {
                    $bytes = @socket_recv($socket,$buffer,2048,0);
                    if($bytes == 0) return;
                    if (!$this->handshake) {
                        // 如果没有握手,先握手回应
                        //doHandShake($socket, $buffer);
                        echo "shakeHandsn";
                    } else {
                        // 如果已经握手,直接接受数据,并处理
                        $buffer = decode($buffer);
                        //process($socket, $buffer);
                        echo "send filen";
                    }
                }
            }
        }
    }
}

上面这段代码是经过我调试了的,没太大的问题,如果想测试的话,可以在 cmd 命令行中键入 php /path/to/demo.php;当然,上面只是一个类,如果要测试的话,还得新建一个实例。

复制代码 代码如下:

$ws = new WS('localhost', 4000);

客户端代码可以稍微简单点:

复制代码 代码如下:

var ws = new WebSocket("ws://localhost:4000");
ws.onopen = function(){
console.log("Handshake successful");
};
ws.onerror = function(){
console.log("error");
};

Run the server code and when the client connects, we can see:

2. Extract Sec-WebSocket-Key information

Copy code The code is as follows:

function getKey($req) {
$key = null;
if (preg_match("/Sec-WebSocket-Key: (.*)rn/", $req, $match)) {
      $key = $match[1];
  }
    return $key ;
}

This is relatively simple, direct regular matching, the websocket information header must contain Sec-WebSocket-Key, so our matching is faster~

3. Encryption Sec-WebSocket-Key

Copy code The code is as follows:

function encry($req){
$key = $this-> getKey($req);
$mask = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

return base64_encode(sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
}

Encrypt the SHA-1 encrypted string with base64 again. If the encryption algorithm is wrong, the client will directly report an error when checking:

4. Response Sec-WebSocket-Accept

Copy code The code is as follows:

function dohandshake($socket, $req){
// Get the encryption key
$ AcceptKey = $ this- & gt; enCry ($ REQ);
$ upgrade = "http/1.1 101 switching propocolsrn". Connection: upgradern ".
           "Sec-WebSocket-Accept: " . $acceptKey . "rn" .
        "rn";

// Write to socket socket_write(socket,$upgrade.chr(0), strlen($upgrade.chr(0)));

// Mark that the handshake has been successful and will be used next time to accept data Data frame format
$this->handshake = true;
}


Be sure to pay attention here. Each request and corresponding format has a blank line at the end, which is rn. I lost this thing when I started testing and struggled with it for a long time.

When the client successfully checks the key, the onopen function will be triggered:

5. Data frame processing


Copy code The code is as follows:
// Parse data frame
function decode ($buffer) {
$len = $masks = $data = $decoded = null;
$len = ord($buffer[1]) & 127;

if ($len === 126) { $masks = substr($buffer, 4, 4);

$data = substr($buffer, 8);
} else if ( $len === 127) {
$masks = substr($buffer, 10, 4);
$data = substr($buffer, 14);
} else {
$masks = substr($buffer, 2, 4);
$data = substr($buffer, 6);
}
for ($index = 0; $index < strlen($data); $index++ ) {
         $decoded .= $data[$index] ^ $masks[$index % 4];
     }
      return $decoded;
}

The encoding issues involved here have been mentioned in the previous article, so I won’t go into details here. PHP has too many functions for character processing, and I don’t remember them very clearly. There is no detailed introduction to the decoding program here, and the client is directly The data sent by the client is returned as it is, which can be regarded as a chat room model.

Copy code The code is as follows:

//Return frame information processing
function frame($s) {
$a = str_split($s, 125);
if (count($a) == 1) {
return "x81" . chr(strlen($a[0])) . $a[ 0];
}
$ns = "";
foreach ($a as $o) {
$ns .= "x81" . chr(strlen($o)) . $o ;
}
return $ns;
}

//Return data
function send($client, $msg){
$msg = $this->frame($msg);
socket_write($client, $msg, strlen( $msg));
}

Client code:

Copy code The code is as follows:

var ws = new WebSocket("ws:// localhost:4000");
ws.onopen = function(){
console.log("Handshake successful");
};
ws.onmessage = function(e){
console.log("message:" + e.data);
};
ws.onerror = function(){
console.log("error");
};
ws.send("Li Jing");

Send data after connection, and the server returns as is:

2. Attention issues

1. websocket version problem

The client's request during the handshake contains Sec-WebSocket-Version: 13, which is a version identifier. This is an upgraded version, and all current browsers use this version. The previous version was more troublesome in the data encryption part. It would send two keys:

Copy the code The code is as follows:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Origin: http://www.jb51.net
Sec-WebSocket- Protocol: chat, superchat
Sec-WebSocket-Key1: xxxx
Sec-WebSocket-Key2: xxxx

If it is this version (older and no longer in use), you need to obtain it through the following method

Copy the code The code is as follows:

function encry($key1,$key2,$l8b){ //Get the numbers preg_match_all('/([d]+)/', $key1, $key1_num); preg_match_all('/( [d]+)/', $key2, $key2_num);

$key1_num = implode($key1_num[0]);
$key2_num = implode($key2_num[0]);
//Count spaces
preg_match_all('/([ ]+)/ ', $key1, $key1_spc);
preg_match_all('/([ ]+)/', $key2, $key2_spc);

if($key1_spc==0|$key2_spc==0){ $this->log("Invalid key");return; }
//Some math
$key1_sec = pack(" N",$key1_num / $key1_spc);
$key2_sec = pack("N",$key2_num / $key2_spc);

return md5($key1_sec.$key2_sec.$l8b,1);
}

I can only complain endlessly about this verification method! Compared with nodeJs's websocket operation mode:

Copy code The code is as follows:

//Server program
var crypto = require('crypto');
var WS = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
require('net').createServer(function(o){
var key;
o.on('data',function(e){
if(!key){
//Handshake
key = e.toString().match(/Sec-WebSocket-Key: ( .+)/)[1];
key = crypto.createHash('sha1').update(key + WS).digest('base64');
o.write('HTTP/1.1 101 Switching Protocolsrn');
o.write('Upgrade: websocketrn');
o.write('Connection: Upgradern');
o.write('Sec-WebSocket-Accept: ' + key + 'rn');
o.write('rn');
}else{
console.log(e);
};
});
}). listen(8000);

2. Data frame parsing code

This article does not provide data frame parsing code such as decodeFrame. The format of the data frame is given in the previous article. Parsing is purely physical work.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/740662.htmlTechArticle Below I drew a diagram to demonstrate the handshake part when establishing a websocket connection between client and server. This part is in node It can be done very easily because the net module provided by node...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles