Home >Common Problem >How many methods are there for tcp long connection subcontracting?

How many methods are there for tcp long connection subcontracting?

coldplay.xixi
coldplay.xixiOriginal
2020-06-28 13:20:263374browse

There are 4 methods for tcp long connection packetization, which are: 1. The method of fixed message length; 2. The method of using special strings as message boundaries; 3. Adding A length field method; 4. A method of subcontracting using the format of the message itself.

How many methods are there for tcp long connection subcontracting?

Four methods of tcp long connection packetization:
1. Fixed message length
2. Use special Strings as message boundaries. For example, the headers of the http protocol use "\r\n" as the field separator
3. Add a length field to the header of each message. This is the most common
4. Use the format of the message itself to subpackage. For example, the pairing of 4216313e5055da45c6d0ded129c5d644c02ae4fdd442eb2210bebb17feeb95b4 in xml, etc.

Related learning recommendations: PHP Programming from beginner to master

Let’s talk about the method of adding message length field to the header for packetization
If each message has a 4-byte header, store the string length. For example, the message "hello", the byte stream is 0x00,0x00,0x00,0x05,'h',' e','l','l','o'
Write a piece of pseudo code to show subcontracting:

void OnMessage()
{    while(接收缓冲buf可读字节>=头部长度4)
    {
        len = 包的长度        if(len>65536 or len<0)
        {
            关闭连接
        }        else if(buf>=len+4)
        {
            从buf中提取出4字节;
            message=将buf后的len长度内存赋给message
            messagecallback(message)调用用户代码处理message
            从buf中移除len长度
        }        else
        {
            不够一个包的长度,等待下次消息到来,break;
        }
    }
}

The above is the detailed content of How many methods are there for tcp long connection subcontracting?. 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

Related articles

See more