search
HomeBackend DevelopmentPHP TutorialDetailed explanation of php using websocket example_PHP tutorial

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                         // 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          $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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),