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
Release: 2020-06-28 13:20:26
Original
3348 people have browsed it

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 <root></root> 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;
        }
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template