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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles