Home  >  Article  >  Backend Development  >  php - tcp packet sticking/unpacking example

php - tcp packet sticking/unpacking example

步履不停
步履不停Original
2019-06-29 17:54:122752browse

php - tcp packet sticking/unpacking example

tcp In long link mode, the fixed message header length method is used to unpack messages to solve the problem of sticky packets.

Fixed message header protocol

Fixes the first N bytes of the message header as the message length bits. Combined with the business scenario, 2bytes or 4bytes, when reading the message, read the message length bit first. You can read the message content according to the specific message length.

pack/unpack can pack values ​​into binary/unpack binary into values. For specific modes, please refer to the detailed usage of pack/unpack. Here we choose a fixed header length of 2 bytes to represent the message body length. The maximum can represent 2 ^16 - 1 length message body, if it is not enough, you can use 4bytes.

Packet grouping

<?php// msg protocol// | ---- dataLen ---- | data |// | - fixed 2bytes  - |// 模拟客户端连续发送2条消息$foo = "hello world";
$bar = "i am sqrt_cat";
$package = "";// 使用 n 打包 固定2bytes$fooLenn = pack("n", strlen($foo));
$package = $fooLenn . $foo;
$barLenn = pack("n", strlen($bar));
$package .= $barLenn . $bar;

sticky package

// send// 传输 $package 由 $foo $bar 两条消息组成 模拟粘包场景
// receive

unpacking

<?php
// 解析第1条消息 取前 2bytes 按 n 解包
$fooLen = unpack("n", substr($package, 0, 2))[1];
// 使用包消息体长度定义读取消息体
// 从第 3byte 开始读 前 2bytes表示长度
$foo = substr($package, 2, $fooLen);
echo $foo . PHP_EOL;

// 解析第2条消息 取前 2bytes 按 n 解包
// 0 ~ (2 + fooLen) - 1 字节序为 fooLen . foo
// (2 + fooLen) ~ (2 + fooLen) + 2 - 1 为 barLen
$barLen = unpack("n", substr($package, (2 + $fooLen), 2))[1];
$bar    = substr($package, (2 + $fooLen) + 2, $barLen);
echo $bar . PHP_EOL;

The tcp scenario often encountered in daily work may be the mode of short connection single message , the client closes the connection after sending a message, and the server reads EOF in a loop to get a complete message. However, if there are multiple messages in a short connection or in a long connection mode, sticky packets may occur, and the client cannot confirm that the message has been read through EOL without closing the server. This requires defining protocols and unpacking.

For more PHP related technical articles, please visit the PHP Tutorial column to learn!

The above is the detailed content of php - tcp packet sticking/unpacking example. For more information, please follow other related articles on the PHP Chinese website!

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