Home >Backend Development >PHP Tutorial >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:
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.
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:
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.
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;当然,上面只是一个类,如果要测试的话,还得新建一个实例。
客户端代码可以稍微简单点:
Run the server code and when the client connects, we can see:
2. Extract Sec-WebSocket-Key information
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
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
// 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
$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.
//Return data
function send($client, $msg){
$msg = $this->frame($msg);
socket_write($client, $msg, strlen( $msg));
}
Client code:
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:
If it is this version (older and no longer in use), you need to obtain it through the following method
$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:
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.