Detailed 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.
① and ② are actually an HTTP request and response, but what we get during the processing is an unparsed string. Such as:
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.
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:
// 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.
//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
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
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
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;
}
When the client successfully checks the key, the onopen function will be triggered:
5. Data frame processing
$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.
//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:
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:
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
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:
//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.

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.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

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 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 remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

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 each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment