TCP利用封包和解包解决“粘包”问题

本文参考自徐晓鑫《后台开发》,给出一个可实际应用的demo,该demo核心在于封包和解包的思想,以及自定义发送、接收数据。

一、TCP粘包现象

what?

TCP是个“流”协议,即没有边界。由于这个特性以及实际的网络情况,在进行数据传输时假设我们连续调用send分别发送两段数据data1和data2,在接收端有以下几种代表性的情况:

  1. 先接收到data1,然后接收到data2。
  2. 先接收到data1的部分数据,然后接收到data1余下的部分以及data2的全部。
  3. 先接收到data1的全部数据和data2的部分数据,然后接收到data2余下的数据。
  4. 一次性接收到了data1和data2的全部数据。

其中,1是理想情况,也就是我们需要的。对于2,3,4的情况就是常说的“粘包”,就需要把接收到的数据进行拆包,拆成一个个独立的数据包,而为了拆包就必须在发送端进行封包。
对于UDP来说不存在拆包问题,因为UDP是一个“数据包“协议,也就是两段数据是有界限的,在接收端要么接收不到数据要么就是一段完整的数据,不会少接收也不会多接收。
这里,笔者在发送端连续发送4096个字节的数据,然后在接收端打印接收到的数据字节数,可以很明显的看到出现了粘包现象。

receive num=2648
------------------------
receive num=1448
------------------------
receive num=2648
------------------------
receive num=2896
------------------------
receive num=1200
------------------------
receive num=1448
------------------------
receive num=2648
------------------------
receive num=2896
------------------------
receive num=1200
------------------------
receive num=1448
------------------------

why?

为什么会出现粘包这种现象呢,以下几点原因。

  1. 由Nagle算法造成的发送端粘包。Nagle算法是一种改善网络传输效率的算法,但也可能造成困扰。简单的说,当提交一端数据给TCP时,TCP并不立刻发送此段数据,而是等待一段时间,看看在等待期间是否还有要发送的数据,若有则会一次吧多段数据发送出去。
  2. 接收端接收不及时造成的接收端粘包。TCP会把接收到的数据存在自己的缓冲区中,然后通知应用层取数据。当应用层由于某些原因不能及时取出TCP的数据,就会造成TCP缓冲区中存放多段数据。
  3. 这种原因是笔者根据实践得出的,不知道对不对。若发送端发送很大的数据包,比如4096字节,由于网卡和路由器中MTU的限制。MTU规定为1500字节,那么每次数据包要低于1500字节(除去IP头部等字节),否则网口以及网络传输途径中路由器等会自动对其进行分包操作。造成接收端并不能一次接收到发送的字节数。

附:
TCP粘包和拆包产生的原因

  1. 应用程序写入数据的字节大小大于套接字发送缓冲区的大小

  2. 进行MSS大小的TCP分段。MSS是最大报文段长度的缩写。MSS是TCP报文段中的数据字段的最大长度。数据字段加上TCP首部才等于整个的TCP报文段。所以MSS并不是TCP报文段的最大长度,而是:MSS=TCP报文段长度-TCP首部长度

  3. 以太网的payload大于MTU进行IP分片。MTU指:一种通信协议的某一层上面所能通过的最大数据包大小。如果IP层有一个数据包要传,而且数据的长度比链路层的MTU大,那么IP层就会进行分片,把数据包分成若干片,让每一片都不超过MTU。注意,IP分片可以发生在原始发送端主机上,也可以发生在中间路由器上。

二、封包和解包

How?

最初解决“粘包”的问题,采用在两次send之间调用sleep休眠小一段时间来解决,缺点是显而易见的:传输效率大大降低,而且也并不可靠。
对数据包进行封包和解包就能解决这个问题:

封包就是给一段数据加上包头,这样一来数据包就分为包头和包体两部分内容了(可加上包尾)。包头其实是一个大小固定的结构体,其中有个结构体成员变量表示包体的长度,这是个很重要的变量,其他的结构体成员可根据需要自己定义。根据固定的包头长度以及包头中含有的包体长度变量值就能正确的拆分出一个完整的数据包。

利用底层的缓冲区来进行拆包时,由于TCP也维护了一个缓冲区,所以可以利用TCP的缓冲区来拆包,也就是循环不停地接收包头给出的数据,直到收够为止,这就是一个完整的TCP包。

三、代码示例

为了解决“粘包”问题,大家通常会在所发送的内容前,加上发送内容的长度,所以对方会先收到4Byte,解析获得接下来所需要接收的长度,再进行收包。
当然这个代码中还有一些待改进的地方:我们并不能保证接收到的4Byte数据正好表示的是数据的实际长度,改进办法是在包头这个结构体变量里添加表示数据头的标志。

发送端:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
/*
客户端给服务端发送一个字符串,由于双方都不知道这个字符串有多长,因此发送数据前的前面4个字节表示字符串的大小
数据格式: 4字节(存储字符串实际长度) + 字符串内容
*/
/*
该函数能够发送指定长度的数据。一次发送不完,可以接着发送,直到发送完指定长度为止
*/
int MySend( int iSock, char * pchBuf, size_t tLen){
        int iThisSend;
        unsigned int iSended=0;//has send bytes
        if(tLen == 0)
               return(0);
        while(iSended<tLen){
              do{
                     iThisSend = send(iSock, pchBuf, tLen-iSended, 0);//this time  
              } while((iThisSend<0) && (errno==EINTR));
               if(iThisSend < 0){
                      return(iSended);
              }
              iSended += iThisSend;
              pchBuf += iThisSend;
       }
        return(tLen);
}

#define DEFAULT_PORT 6666

int main( int argc, char * argv[]){
    int connfd = 0;
    int cLen = 0;
    struct sockaddr_in client;
    if(argc < 2){
        printf(" Uasge: clientent [server IP address]\n");
        return -1;
    }
    client.sin_family = AF_INET;
    client.sin_port = htons(DEFAULT_PORT);
    client.sin_addr.s_addr = inet_addr(argv[1]);
    connfd = socket(AF_INET, SOCK_STREAM, 0);
    if(connfd < 0){
        printf("socket() failure!\n" );
        return -1;
    }

    if(connect(connfd, (struct sockaddr*)&client, sizeof(client)) < 0){
        printf("connect() failure!\n" );
        return -1;
    }
    //
    ssize_t writeLen;
    char *sendMsg = "0123456789";
    int tLen=strlen(sendMsg);
    printf("tLen:%d\n" ,tLen);
    int iLen=0;
    char * pBuff= new char [100];
    *(int*)(pBuff+iLen)= htonl(tLen);
    iLen+=sizeof( int);
    memcpy(pBuff+iLen,sendMsg,tLen);
    iLen+=tLen;
    writeLen= MySend(connfd, pBuff, iLen);
    if (writeLen < 0) {
       printf("write failed\n" );
       close(connfd);
       return 0;
    }
    else{
       printf("write sucess, writelen :%d, sendMsg:%s\n",writeLen,sendMsg);
    }
    close(connfd);
    return 0;
}

服务器端:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>

/*
该函数能够接受指定长度(字节)的数据。循环接收,直到接受完指定数量为止。
*/
int MyRecv( int iSock, char * pchBuf, size_t tCount){
        size_t tBytesRead=0;
        int iThisRead;
        while(tBytesRead < tCount){
              do{
                     iThisRead = read(iSock, pchBuf, tCount-tBytesRead);
              } while((iThisRead<0) && (errno==EINTR));
              if(iThisRead < 0){
                      return(iThisRead);
              }else if (iThisRead == 0)
                      return(tBytesRead);
              tBytesRead += iThisRead;
              pchBuf += iThisRead;
       }
}

#define DEFAULT_PORT 6666
int main( int argc, char ** argv){
    int sockfd,acceptfd; /* 监听socket: sock_fd,数据传输socket: acceptfd */
    struct sockaddr_in my_addr; /* 本机地址信息 */
    struct sockaddr_in their_addr; /* 客户地址信息 */
    unsigned int sin_size, myport=6666, lisnum=10;
    if ((sockfd = socket(AF_INET , SOCK_STREAM, 0)) == -1) {
       perror("socket" );
       return -1;
    }

    printf("socket ok \n");
    my_addr.sin_family=AF_INET;
    my_addr.sin_port=htons(DEFAULT_PORT);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(my_addr.sin_zero), 0);

    if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr )) == -1) {
        perror("bind" );
        return -2;
    }

    printf("bind ok \n");
    if (listen(sockfd, lisnum) == -1) {
        perror("listen" );
        return -3;
    }
    printf("listen ok \n");
    char recvMsg[10];
    sin_size = sizeof(my_addr);
    acceptfd = accept(sockfd,(struct sockaddr *)&my_addr,&sin_size);
    if (acceptfd < 0) {
       close(sockfd);
       printf("accept failed\n" );
       return -4;
    }

    ssize_t readLen = MyRecv(acceptfd, recvMsg, sizeof( int));
    if (readLen < 0) {
       printf("read failed\n" );
       return -1;
    }

    int len=( int)ntohl(*( int*)recvMsg);
    printf("len:%d\n",len);
    readLen = MyRecv(acceptfd, recvMsg, len);
    if (readLen < 0) {
       printf("read failed\n" );
       return -1;
    }
    recvMsg[len]='\0';//接收到的数据并没有结束符'\0',因此需要加上结束符'\0
    printf("recvMsg:%s\n" ,recvMsg);
    close(acceptfd);
    return 0;
  }

Makefile:

all:tcpServer tcpClient
tcpServer:tcpServer.o
    gcc -g -o tcpServer tcpServer.o
tcpClient:tcpClient.o
    gcc -g -o tcpClient tcpClient.o
tcpServer.o:tcpServer.c
    gcc -g -c tcpServer.c
tcpClient.o:tcpClient.c
    gcc -g -c tcpClient.c
clean:all
    rm all

运行截图:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u013457167/article/details/80111301