Websocket消息帧粘包,拆包及处理方法

转载 https://blog.csdn.net/yangzai187/article/details/93905594

 

问题:

        接收客户端消息处理时,遇到这样情况;接收第一帧数据时正常的,后面再次接受解析数据帧时,发现解析的消息是异常、缺失的,导致服务端不能正确接收消息。

       查了相关资料,发现tcp再传输数据时,发送消息并非一包一包发送,存在粘包、拆包的情况。

粘包、拆包表现形式

现在假设客户端向服务端连续发送了两个数据包,用packet1和packet2来表示,那么服务端收到的数据可以分为三种,现列举如下:

第一种情况(正常情况)

      接收端正常收到两个数据包,即没有发生拆包和粘包的现象,此种情况不在本文的讨论范围内。normal

第二种情况(粘包:两帧数据放在一个tcp消息包中)

     接收端只收到一个数据包,由于TCP是不会出现丢包的,所以这一个数据包中包含了发送端发送的两个数据包的信息,这种现象即为粘包。这种情况由于接收端不知道这两个数据包的界限,所以对于接收端来说很难处理。one

第三种情况(拆包:一帧数据被拆分在两个tcp消息包中)

      这种情况有两种表现形式,如下图。接收端收到了两个数据包,但是这两个数据包要么是不完整的,要么就是多出来一块,这种情况即发生了拆包和粘包。这两种情况如果不加特殊处理,对于接收端同样是不好处理的。half_oneone_half

粘包、拆包发生原因

    发生TCP粘包或拆包有很多原因,现列出常见的几点,可能不全面,欢迎补充,

    1、要发送的数据大于TCP发送缓冲区剩余空间大小,将会发生拆包。

    2、待发送数据大于MSS(最大报文长度),TCP在传输前将进行拆包。

    3、要发送的数据小于TCP发送缓冲区的大小,TCP将多次写入缓冲区的数据一次发送出去,将会发生粘包。

    4、接收数据端的应用层没有及时读取接收缓冲区中的数据,将发生粘包。

    等等。

粘包、拆包解决办法

    通过以上分析,我们清楚了粘包或拆包发生的原因,那么如何解决这个问题呢?解决问题的关键在于如何给每个数据包添加边界信息,常用的方法有如下几个:

    1、发送端给每个数据包添加包首部,首部中应该至少包含数据包的长度,这样接收端在接收到数据后,通过读取包首部的长度字段,便知道每一个数据包的实际长度了。

    2、发送端将每个数据包封装为固定长度(不够的可以通过补0填充),这样接收端每次从接收缓冲区中读取固定长度的数据就自然而然的把每个数据包拆分开来。

    3、可以在数据包之间设置边界,如添加特殊符号,这样,接收端通过这个边界就可以将不同的数据包拆分开。

    等等。

 

样例程序

    我将在程序中使用两种方法来解决粘包和拆包问题,固定数据包长度和添加长度首部,这两种方法各有优劣。

    固定数据包长度传输效率一般,尤其是在要发送的数据长度长短差别很大的时候效率会比较低,但是编程实现比较简单;

    添加长度首部虽然可以获得较高的传输效率,冗余信息少且固定,但是编程实现较为复杂。

     websocket是包含消息头部的,所以样例程序采用首部验证方法

固定数据包长度

这种处理方式的思路很简单,发送端在发送实际数据前先把数据封装为固定长度,然后在发送出去,接收端接收到数据后按照这个固定长度进行拆分即可。处理省略。。。

添加长度首部

这种方式的处理较上面提到的方式稍微复杂一点。在发送端需要给待发送的数据添加固定的首部,然后再发送出去,然后在接收端需要根据这个首部的长度信息进行数据包的组合或拆分,发送端程序如下:

 

  1.  
     
  2.  
    #include "websocket_common.h"
  3.  
     
  4.  
    #include <stdio.h>
  5.  
    #include <stdlib.h>
  6.  
    #include <string.h> // 使用 malloc, calloc等动态分配内存方法
  7.  
    #include <time.h> // 获取系统时间
  8.  
    #include <errno.h>
  9.  
    #include <fcntl.h> // 非阻塞
  10.  
    #include <sys/un.h>
  11.  
    #include <arpa/inet.h> // inet_addr()
  12.  
    #include <unistd.h> // close()
  13.  
    #include <sys/types.h> // 文件IO操作
  14.  
    #include <sys/socket.h> //
  15.  
    #include <netinet/in.h>
  16.  
    #include <netinet/ip.h>
  17.  
    #include <netinet/ip_icmp.h>
  18.  
    #include <netdb.h> // gethostbyname, gethostbyname2, gethostbyname_r, gethostbyname_r2
  19.  
    #include <sys/un.h>
  20.  
    #include <sys/time.h>
  21.  
    #include <arpa/inet.h>
  22.  
    #include <net/if.h>
  23.  
    #include <sys/ioctl.h> // SIOCSIFADDR
  24.  
     
  25.  
    //==============================================================================================
  26.  
    //======================================== 设置和工具部分 =======================================
  27.  
    //==============================================================================================
  28.  
     
  29.  
    // 连接服务器
  30.  
    #define WEBSOCKET_LOGIN_CONNECT_TIMEOUT 1000 // 登录连接超时设置 1000ms
  31.  
    #define WEBSOCKET_LOGIN_RESPOND_TIMEOUT (1000 + WEBSOCKET_LOGIN_CONNECT_TIMEOUT) // 登录等待回应超时设置 1000ms
  32.  
    // 发收
  33.  
    // 生成握手key的长度
  34.  
    #define WEBSOCKET_SHAKE_KEY_LEN 16
  35.  
     
  36.  
    //==================== delay ms ====================
  37.  
    void webSocket_delayms(unsigned int ms)
  38.  
    {
  39.  
    struct timeval tim;
  40.  
    tim.tv_sec = ms/1000;
  41.  
    tim.tv_usec = (ms%1000)*1000;
  42.  
    select(0, NULL, NULL, NULL, &tim);
  43.  
    }
  44.  
     
  45.  
    //-------------------- IP控制 --------------------
  46.  
     
  47.  
    int netCheck_setIP(char *devName, char *ip)
  48.  
    {
  49.  
    struct ifreq temp;
  50.  
    struct sockaddr_in *addr;
  51.  
    int fd, ret;
  52.  
    //
  53.  
    strcpy(temp.ifr_name, devName);
  54.  
    if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  55.  
    return -1;
  56.  
    //
  57.  
    addr = (struct sockaddr_in *)&(temp.ifr_addr);
  58.  
    addr->sin_family = AF_INET;
  59.  
    addr->sin_addr.s_addr = inet_addr(ip);
  60.  
    ret = ioctl(fd, SIOCSIFADDR, &temp);
  61.  
    //
  62.  
    close(fd);
  63.  
    if(ret < 0)
  64.  
    return -1;
  65.  
    return 0;
  66.  
    }
  67.  
     
  68.  
    void netCheck_getIP(char *devName, char *ip)
  69.  
    {
  70.  
    struct ifreq temp;
  71.  
    struct sockaddr_in *addr;
  72.  
    int fd, ret;
  73.  
    //
  74.  
    strcpy(temp.ifr_name, devName);
  75.  
    if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  76.  
    return;
  77.  
    ret = ioctl(fd, SIOCGIFADDR, &temp);
  78.  
    close(fd);
  79.  
    if(ret < 0)
  80.  
    return;
  81.  
    //
  82.  
    addr = (struct sockaddr_in *)&(temp.ifr_addr);
  83.  
    strcpy(ip, inet_ntoa(addr->sin_addr));
  84.  
    //
  85.  
    // return ip;
  86.  
    }
  87.  
     
  88.  
    //==================== 域名转IP ====================
  89.  
     
  90.  
    typedef struct{
  91.  
    pthread_t thread_id;
  92.  
    char ip[256];
  93.  
    bool result;
  94.  
    bool actionEnd;
  95.  
    }GetHostName_Struct;
  96.  
    //
  97.  
    void *websocket_getHost_fun(void *arge)
  98.  
    {
  99.  
    int ret;
  100.  
    //int i;
  101.  
    char buf[1024];
  102.  
    struct hostent host_body, *host = NULL;
  103.  
    struct in_addr **addr_list;
  104.  
    GetHostName_Struct *gs = (GetHostName_Struct *)arge;
  105.  
     
  106.  
    /* 此类方法不可重入! 即使关闭线程
  107.  
    if((host = gethostbyname(gs->ip)) == NULL)
  108.  
    //if((host = gethostbyname2(gs->ip, AF_INET)) == NULL)
  109.  
    {
  110.  
    gs->actionEnd = true;
  111.  
    return NULL;
  112.  
    }*/
  113.  
    if(gethostbyname_r(gs->ip, &host_body, buf, sizeof(buf), &host, &ret))
  114.  
    {
  115.  
    gs->actionEnd = true;
  116.  
    return NULL;
  117.  
    }
  118.  
    if(host == NULL)
  119.  
    {
  120.  
    gs->actionEnd = true;
  121.  
    return NULL;
  122.  
    }
  123.  
    addr_list = (struct in_addr **)host->h_addr_list;
  124.  
    //printf("ip name : %s\r\nip list : ", host->h_name);
  125.  
    //for(i = 0; addr_list[i] != NULL; i++) printf("%s, ", inet_ntoa(*addr_list[i])); printf("\r\n");
  126.  
    if(addr_list[0] == NULL)
  127.  
    {
  128.  
    gs->actionEnd = true;
  129.  
    return NULL;
  130.  
    }
  131.  
    memset(gs->ip, 0, sizeof(gs->ip));
  132.  
    strcpy(gs->ip, (char *)(inet_ntoa(*addr_list[0])));
  133.  
    gs->result = true;
  134.  
    gs->actionEnd = true;
  135.  
    return NULL;
  136.  
    }
  137.  
    //
  138.  
    int websocket_getIpByHostName(char *hostName, char *backIp)
  139.  
    {
  140.  
    int i, timeOut = 1;
  141.  
    GetHostName_Struct gs;
  142.  
    if(hostName == NULL)
  143.  
    return -1;
  144.  
    else if(strlen(hostName) < 1)
  145.  
    return -1;
  146.  
    //----- 开线程从域名获取IP -----
  147.  
    memset(&gs, 0, sizeof(GetHostName_Struct));
  148.  
    strcpy(gs.ip, hostName);
  149.  
    gs.result = false;
  150.  
    gs.actionEnd = false;
  151.  
    if (pthread_create(&gs.thread_id, NULL, (void *)websocket_getHost_fun, &gs) < 0)
  152.  
    return -1;
  153.  
    i = 0;
  154.  
    while(!gs.actionEnd)
  155.  
    {
  156.  
    if(++i > 10)
  157.  
    {
  158.  
    i = 0;
  159.  
    if(++timeOut > 1000)
  160.  
    break;
  161.  
    }
  162.  
    webSocket_delayms(1000);// 1ms延时
  163.  
    }
  164.  
    // pthread_cancel(gs.thread_id);
  165.  
    pthread_join(gs.thread_id, NULL);
  166.  
    if(!gs.result)
  167.  
    return -timeOut;
  168.  
    //----- 开线程从域名获取IP -----
  169.  
    memset(backIp, 0, strlen(backIp));
  170.  
    strcpy(backIp, gs.ip);
  171.  
    return timeOut;
  172.  
    }
  173.  
     
  174.  
    //==================== 加密方法BASE64 ====================
  175.  
     
  176.  
    //base64编/解码用的基础字符集
  177.  
    const char websocket_base64char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  178.  
     
  179.  
    /*******************************************************************************
  180.  
    * 名称: websocket_base64_encode
  181.  
    * 功能: ascii编码为base64格式
  182.  
    * 形参: bindata : ascii字符串输入
  183.  
    * base64 : base64字符串输出
  184.  
    * binlength : bindata的长度
  185.  
    * 返回: base64字符串长度
  186.  
    * 说明: 无
  187.  
    ******************************************************************************/
  188.  
    int websocket_base64_encode( const unsigned char *bindata, char *base64, int binlength)
  189.  
    {
  190.  
    int i, j;
  191.  
    unsigned char current;
  192.  
    for ( i = 0, j = 0 ; i < binlength ; i += 3 )
  193.  
    {
  194.  
    current = (bindata[i] >> 2) ;
  195.  
    current &= (unsigned char)0x3F;
  196.  
    base64[j++] = websocket_base64char[(int)current];
  197.  
    current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
  198.  
    if ( i + 1 >= binlength )
  199.  
    {
  200.  
    base64[j++] = websocket_base64char[(int)current];
  201.  
    base64[j++] = '=';
  202.  
    base64[j++] = '=';
  203.  
    break;
  204.  
    }
  205.  
    current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
  206.  
    base64[j++] = websocket_base64char[(int)current];
  207.  
    current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
  208.  
    if ( i + 2 >= binlength )
  209.  
    {
  210.  
    base64[j++] = websocket_base64char[(int)current];
  211.  
    base64[j++] = '=';
  212.  
    break;
  213.  
    }
  214.  
    current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
  215.  
    base64[j++] = websocket_base64char[(int)current];
  216.  
    current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
  217.  
    base64[j++] = websocket_base64char[(int)current];
  218.  
    }
  219.  
    base64[j] = '\0';
  220.  
    return j;
  221.  
    }
  222.  
    /*******************************************************************************
  223.  
    * 名称: websocket_base64_decode
  224.  
    * 功能: base64格式解码为ascii
  225.  
    * 形参: base64 : base64字符串输入
  226.  
    * bindata : ascii字符串输出
  227.  
    * 返回: 解码出来的ascii字符串长度
  228.  
    * 说明: 无
  229.  
    ******************************************************************************/
  230.  
    int websocket_base64_decode( const char *base64, unsigned char *bindata)
  231.  
    {
  232.  
    int i, j;
  233.  
    unsigned char k;
  234.  
    unsigned char temp[4];
  235.  
    for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 )
  236.  
    {
  237.  
    memset( temp, 0xFF, sizeof(temp) );
  238.  
    for ( k = 0 ; k < 64 ; k ++ )
  239.  
    {
  240.  
    if ( websocket_base64char[k] == base64[i] )
  241.  
    temp[0]= k;
  242.  
    }
  243.  
    for ( k = 0 ; k < 64 ; k ++ )
  244.  
    {
  245.  
    if ( websocket_base64char[k] == base64[i+1] )
  246.  
    temp[1]= k;
  247.  
    }
  248.  
    for ( k = 0 ; k < 64 ; k ++ )
  249.  
    {
  250.  
    if ( websocket_base64char[k] == base64[i+2] )
  251.  
    temp[2]= k;
  252.  
    }
  253.  
    for ( k = 0 ; k < 64 ; k ++ )
  254.  
    {
  255.  
    if ( websocket_base64char[k] == base64[i+3] )
  256.  
    temp[3]= k;
  257.  
    }
  258.  
    bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) | \
  259.  
    ((unsigned char)((unsigned char)(temp[1]>>4)&0x03));
  260.  
    if ( base64[i+2] == '=' )
  261.  
    break;
  262.  
    bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) | \
  263.  
    ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F));
  264.  
    if ( base64[i+3] == '=' )
  265.  
    break;
  266.  
    bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) | \
  267.  
    ((unsigned char)(temp[3]&0x3F));
  268.  
    }
  269.  
    return j;
  270.  
    }
  271.  
     
  272.  
    //==================== 加密方法 sha1哈希 ====================
  273.  
     
  274.  
    typedef struct SHA1Context{
  275.  
    unsigned Message_Digest[5];
  276.  
    unsigned Length_Low;
  277.  
    unsigned Length_High;
  278.  
    unsigned char Message_Block[64];
  279.  
    int Message_Block_Index;
  280.  
    int Computed;
  281.  
    int Corrupted;
  282.  
    } SHA1Context;
  283.  
     
  284.  
    #define SHA1CircularShift(bits,word) ((((word) << (bits)) & 0xFFFFFFFF) | ((word) >> (32-(bits))))
  285.  
     
  286.  
    void SHA1ProcessMessageBlock(SHA1Context *context)
  287.  
    {
  288.  
    const unsigned K[] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
  289.  
    int t;
  290.  
    unsigned temp;
  291.  
    unsigned W[80];
  292.  
    unsigned A, B, C, D, E;
  293.  
     
  294.  
    for(t = 0; t < 16; t++)
  295.  
    {
  296.  
    W[t] = ((unsigned) context->Message_Block[t * 4]) << 24;
  297.  
    W[t] |= ((unsigned) context->Message_Block[t * 4 + 1]) << 16;
  298.  
    W[t] |= ((unsigned) context->Message_Block[t * 4 + 2]) << 8;
  299.  
    W[t] |= ((unsigned) context->Message_Block[t * 4 + 3]);
  300.  
    }
  301.  
     
  302.  
    for(t = 16; t < 80; t++)
  303.  
    W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
  304.  
     
  305.  
    A = context->Message_Digest[0];
  306.  
    B = context->Message_Digest[1];
  307.  
    C = context->Message_Digest[2];
  308.  
    D = context->Message_Digest[3];
  309.  
    E = context->Message_Digest[4];
  310.  
     
  311.  
    for(t = 0; t < 20; t++)
  312.  
    {
  313.  
    temp = SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0];
  314.  
    temp &= 0xFFFFFFFF;
  315.  
    E = D;
  316.  
    D = C;
  317.  
    C = SHA1CircularShift(30,B);
  318.  
    B = A;
  319.  
    A = temp;
  320.  
    }
  321.  
    for(t = 20; t < 40; t++)
  322.  
    {
  323.  
    temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
  324.  
    temp &= 0xFFFFFFFF;
  325.  
    E = D;
  326.  
    D = C;
  327.  
    C = SHA1CircularShift(30,B);
  328.  
    B = A;
  329.  
    A = temp;
  330.  
    }
  331.  
    for(t = 40; t < 60; t++)
  332.  
    {
  333.  
    temp = SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2];
  334.  
    temp &= 0xFFFFFFFF;
  335.  
    E = D;
  336.  
    D = C;
  337.  
    C = SHA1CircularShift(30,B);
  338.  
    B = A;
  339.  
    A = temp;
  340.  
    }
  341.  
    for(t = 60; t < 80; t++)
  342.  
    {
  343.  
    temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3];
  344.  
    temp &= 0xFFFFFFFF;
  345.  
    E = D;
  346.  
    D = C;
  347.  
    C = SHA1CircularShift(30,B);
  348.  
    B = A;
  349.  
    A = temp;
  350.  
    }
  351.  
    context->Message_Digest[0] = (context->Message_Digest[0] + A) & 0xFFFFFFFF;
  352.  
    context->Message_Digest[1] = (context->Message_Digest[1] + B) & 0xFFFFFFFF;
  353.  
    context->Message_Digest[2] = (context->Message_Digest[2] + C) & 0xFFFFFFFF;
  354.  
    context->Message_Digest[3] = (context->Message_Digest[3] + D) & 0xFFFFFFFF;
  355.  
    context->Message_Digest[4] = (context->Message_Digest[4] + E) & 0xFFFFFFFF;
  356.  
    context->Message_Block_Index = 0;
  357.  
    }
  358.  
     
  359.  
    void SHA1Reset(SHA1Context *context)
  360.  
    {
  361.  
    context->Length_Low = 0;
  362.  
    context->Length_High = 0;
  363.  
    context->Message_Block_Index = 0;
  364.  
     
  365.  
    context->Message_Digest[0] = 0x67452301;
  366.  
    context->Message_Digest[1] = 0xEFCDAB89;
  367.  
    context->Message_Digest[2] = 0x98BADCFE;
  368.  
    context->Message_Digest[3] = 0x10325476;
  369.  
    context->Message_Digest[4] = 0xC3D2E1F0;
  370.  
     
  371.  
    context->Computed = 0;
  372.  
    context->Corrupted = 0;
  373.  
    }
  374.  
     
  375.  
    void SHA1PadMessage(SHA1Context *context)
  376.  
    {
  377.  
    if (context->Message_Block_Index > 55)
  378.  
    {
  379.  
    context->Message_Block[context->Message_Block_Index++] = 0x80;
  380.  
    while(context->Message_Block_Index < 64) context->Message_Block[context->Message_Block_Index++] = 0;
  381.  
    SHA1ProcessMessageBlock(context);
  382.  
    while(context->Message_Block_Index < 56) context->Message_Block[context->Message_Block_Index++] = 0;
  383.  
    }
  384.  
    else
  385.  
    {
  386.  
    context->Message_Block[context->Message_Block_Index++] = 0x80;
  387.  
    while(context->Message_Block_Index < 56) context->Message_Block[context->Message_Block_Index++] = 0;
  388.  
    }
  389.  
    context->Message_Block[56] = (context->Length_High >> 24 ) & 0xFF;
  390.  
    context->Message_Block[57] = (context->Length_High >> 16 ) & 0xFF;
  391.  
    context->Message_Block[58] = (context->Length_High >> 8 ) & 0xFF;
  392.  
    context->Message_Block[59] = (context->Length_High) & 0xFF;
  393.  
    context->Message_Block[60] = (context->Length_Low >> 24 ) & 0xFF;
  394.  
    context->Message_Block[61] = (context->Length_Low >> 16 ) & 0xFF;
  395.  
    context->Message_Block[62] = (context->Length_Low >> 8 ) & 0xFF;
  396.  
    context->Message_Block[63] = (context->Length_Low) & 0xFF;
  397.  
     
  398.  
    SHA1ProcessMessageBlock(context);
  399.  
    }
  400.  
     
  401.  
    int SHA1Result(SHA1Context *context)
  402.  
    {
  403.  
    if (context->Corrupted)
  404.  
    {
  405.  
    return 0;
  406.  
    }
  407.  
    if (!context->Computed)
  408.  
    {
  409.  
    SHA1PadMessage(context);
  410.  
    context->Computed = 1;
  411.  
    }
  412.  
    return 1;
  413.  
    }
  414.  
     
  415.  
     
  416.  
    void SHA1Input(SHA1Context *context,const char *message_array,unsigned length){
  417.  
    if (!length)
  418.  
    return;
  419.  
     
  420.  
    if (context->Computed || context->Corrupted)
  421.  
    {
  422.  
    context->Corrupted = 1;
  423.  
    return;
  424.  
    }
  425.  
     
  426.  
    while(length-- && !context->Corrupted)
  427.  
    {
  428.  
    context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF);
  429.  
     
  430.  
    context->Length_Low += 8;
  431.  
     
  432.  
    context->Length_Low &= 0xFFFFFFFF;
  433.  
    if (context->Length_Low == 0)
  434.  
    {
  435.  
    context->Length_High++;
  436.  
    context->Length_High &= 0xFFFFFFFF;
  437.  
    if (context->Length_High == 0) context->Corrupted = 1;
  438.  
    }
  439.  
     
  440.  
    if (context->Message_Block_Index == 64)
  441.  
    {
  442.  
    SHA1ProcessMessageBlock(context);
  443.  
    }
  444.  
    message_array++;
  445.  
    }
  446.  
    }
  447.  
     
  448.  
    /*
  449.  
    int sha1_hash(const char *source, char *lrvar){// Main
  450.  
    SHA1Context sha;
  451.  
    char buf[128];
  452.  
     
  453.  
    SHA1Reset(&sha);
  454.  
    SHA1Input(&sha, source, strlen(source));
  455.  
     
  456.  
    if (!SHA1Result(&sha)){
  457.  
    printf("SHA1 ERROR: Could not compute message digest");
  458.  
    return -1;
  459.  
    } else {
  460.  
    memset(buf,0,sizeof(buf));
  461.  
    sprintf(buf, "%08X%08X%08X%08X%08X", sha.Message_Digest[0],sha.Message_Digest[1],
  462.  
    sha.Message_Digest[2],sha.Message_Digest[3],sha.Message_Digest[4]);
  463.  
    //lr_save_string(buf, lrvar);
  464.  
     
  465.  
    return strlen(buf);
  466.  
    }
  467.  
    }
  468.  
    */
  469.  
    char * sha1_hash(const char *source){ // Main
  470.  
    SHA1Context sha;
  471.  
    char *buf;//[128];
  472.  
     
  473.  
    SHA1Reset(&sha);
  474.  
    SHA1Input(&sha, source, strlen(source));
  475.  
     
  476.  
    if (!SHA1Result(&sha))
  477.  
    {
  478.  
    printf("SHA1 ERROR: Could not compute message digest");
  479.  
    return NULL;
  480.  
    }
  481.  
    else
  482.  
    {
  483.  
    buf = (char *)malloc(128);
  484.  
    memset(buf, 0, 128);
  485.  
    sprintf(buf, "%08X%08X%08X%08X%08X", sha.Message_Digest[0],sha.Message_Digest[1],
  486.  
    sha.Message_Digest[2],sha.Message_Digest[3],sha.Message_Digest[4]);
  487.  
    //lr_save_string(buf, lrvar);
  488.  
     
  489.  
    //return strlen(buf);
  490.  
    return buf;
  491.  
    }
  492.  
    }
  493.  
     
  494.  
    int tolower(int c)
  495.  
    {
  496.  
    if (c >= 'A' && c <= 'Z')
  497.  
    {
  498.  
    return c + 'a' - 'A';
  499.  
    }
  500.  
    else
  501.  
    {
  502.  
    return c;
  503.  
    }
  504.  
    }
  505.  
     
  506.  
    int htoi(const char s[], int start, int len)
  507.  
    {
  508.  
    int i, j;
  509.  
    int n = 0;
  510.  
    if (s[0] == '0' && (s[1]=='x' || s[1]=='X')) //判断是否有前导0x或者0X
  511.  
    {
  512.  
    i = 2;
  513.  
    }
  514.  
    else
  515.  
    {
  516.  
    i = 0;
  517.  
    }
  518.  
    i+=start;
  519.  
    j=0;
  520.  
    for (; (s[i] >= '0' && s[i] <= '9')
  521.  
    || (s[i] >= 'a' && s[i] <= 'f') || (s[i] >='A' && s[i] <= 'F');++i)
  522.  
    {
  523.  
    if(j>=len)
  524.  
    {
  525.  
    break;
  526.  
    }
  527.  
    if (tolower(s[i]) > '9')
  528.  
    {
  529.  
    n = 16 * n + (10 + tolower(s[i]) - 'a');
  530.  
    }
  531.  
    else
  532.  
    {
  533.  
    n = 16 * n + (tolower(s[i]) - '0');
  534.  
    }
  535.  
    j++;
  536.  
    }
  537.  
    return n;
  538.  
    }
  539.  
     
  540.  
    //==============================================================================================
  541.  
    //======================================== websocket部分 =======================================
  542.  
    //==============================================================================================
  543.  
     
  544.  
    // websocket根据data[0]判别数据包类型
  545.  
    // typedef enum{
  546.  
    // WDT_MINDATA = -20, // 0x0:标识一个中间数据包
  547.  
    // WDT_TXTDATA = -19, // 0x1:标识一个text类型数据包
  548.  
    // WDT_BINDATA = -18, // 0x2:标识一个binary类型数据包
  549.  
    // WDT_DISCONN = -17, // 0x8:标识一个断开连接类型数据包
  550.  
    // WDT_PING = -16, // 0x8:标识一个断开连接类型数据包
  551.  
    // WDT_PONG = -15, // 0xA:表示一个pong类型数据包
  552.  
    // WDT_ERR = -1,
  553.  
    // WDT_NULL = 0
  554.  
    // }WebsocketData_Type;
  555.  
    /*******************************************************************************
  556.  
    * 名称: webSocket_getRandomString
  557.  
    * 功能: 生成随机字符串
  558.  
    * 形参: *buf:随机字符串存储到
  559.  
    * len : 生成随机字符串长度
  560.  
    * 返回: 无
  561.  
    * 说明: 无
  562.  
    ******************************************************************************/
  563.  
    void webSocket_getRandomString(unsigned char *buf, unsigned int len)
  564.  
    {
  565.  
    unsigned int i;
  566.  
    unsigned char temp;
  567.  
    srand((int)time(0));
  568.  
    for(i = 0; i < len; i++)
  569.  
    {
  570.  
    temp = (unsigned char)(rand()%256);
  571.  
    if(temp == 0) // 随机数不要0, 0 会干扰对字符串长度的判断
  572.  
    temp = 128;
  573.  
    buf[i] = temp;
  574.  
    }
  575.  
    }
  576.  
    /*******************************************************************************
  577.  
    * 名称: webSocket_buildShakeKey
  578.  
    * 功能: client端使用随机数构建握手用的key
  579.  
    * 形参: *key:随机生成的握手key
  580.  
    * 返回: key的长度
  581.  
    * 说明: 无
  582.  
    ******************************************************************************/
  583.  
    int webSocket_buildShakeKey(unsigned char *key)
  584.  
    {
  585.  
    unsigned char tempKey[WEBSOCKET_SHAKE_KEY_LEN] = {0};
  586.  
    webSocket_getRandomString(tempKey, WEBSOCKET_SHAKE_KEY_LEN);
  587.  
    return websocket_base64_encode((const unsigned char *)tempKey, (char *)key, WEBSOCKET_SHAKE_KEY_LEN);
  588.  
    }
  589.  
    /*******************************************************************************
  590.  
    * 名称: webSocket_buildRespondShakeKey
  591.  
    * 功能: server端在接收client端的key后,构建回应用的key
  592.  
    * 形参: *acceptKey:来自客户端的key字符串
  593.  
    * acceptKeyLen : 长度
  594.  
    * *respondKey : 在 acceptKey 之后加上 GUID, 再sha1哈希, 再转成base64得到 respondKey
  595.  
    * 返回: respondKey的长度(肯定比acceptKey要长)
  596.  
    * 说明: 无
  597.  
    ******************************************************************************/
  598.  
    int webSocket_buildRespondShakeKey(unsigned char *acceptKey, unsigned int acceptKeyLen, unsigned char *respondKey)
  599.  
    {
  600.  
    char *clientKey;
  601.  
    char *sha1DataTemp;
  602.  
    char *sha1Data;
  603.  
    int i, n;
  604.  
    const char GUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  605.  
    unsigned int GUIDLEN;
  606.  
     
  607.  
    if(acceptKey == NULL)
  608.  
    return 0;
  609.  
    GUIDLEN = sizeof(GUID);
  610.  
    clientKey = (char *)calloc(acceptKeyLen + GUIDLEN + 10, sizeof(char));
  611.  
    memset(clientKey, 0, (acceptKeyLen + GUIDLEN + 10));
  612.  
    //
  613.  
    memcpy(clientKey, acceptKey, acceptKeyLen);
  614.  
    memcpy(&clientKey[acceptKeyLen], GUID, GUIDLEN);
  615.  
    clientKey[acceptKeyLen + GUIDLEN] = '\0';
  616.  
    //
  617.  
    sha1DataTemp = sha1_hash(clientKey);
  618.  
    n = strlen((const char *)sha1DataTemp);
  619.  
    sha1Data = (char *)calloc(n / 2 + 1, sizeof(char));
  620.  
    memset(sha1Data, 0, n / 2 + 1);
  621.  
    //
  622.  
    for(i = 0; i < n; i += 2)
  623.  
    sha1Data[ i / 2 ] = htoi(sha1DataTemp, i, 2);
  624.  
    n = websocket_base64_encode((const unsigned char *)sha1Data, (char *)respondKey, (n / 2));
  625.  
    //
  626.  
    free(sha1DataTemp);
  627.  
    free(sha1Data);
  628.  
    free(clientKey);
  629.  
    return n;
  630.  
    }
  631.  
    /*******************************************************************************
  632.  
    * 名称: webSocket_matchShakeKey
  633.  
    * 功能: client端收到来自服务器回应的key后进行匹配,以验证握手成功
  634.  
    * 形参: *myKey:client端请求握手时发给服务器的key
  635.  
    * myKeyLen : 长度
  636.  
    * *acceptKey : 服务器回应的key
  637.  
    * acceptKeyLen : 长度
  638.  
    * 返回: 0 成功 -1 失败
  639.  
    * 说明: 无
  640.  
    ******************************************************************************/
  641.  
    int webSocket_matchShakeKey(unsigned char *myKey, unsigned int myKeyLen, unsigned char *acceptKey, unsigned int acceptKeyLen)
  642.  
    {
  643.  
    int retLen;
  644.  
    unsigned char tempKey[256] = {0};
  645.  
    //
  646.  
    retLen = webSocket_buildRespondShakeKey(myKey, myKeyLen, tempKey);
  647.  
    //printf("webSocket_matchShakeKey :\r\n%d : %s\r\n%d : %s\r\n", acceptKeyLen, acceptKey, retLen, tempKey);
  648.  
    //
  649.  
    if(retLen != acceptKeyLen)
  650.  
    {
  651.  
    printf("webSocket_matchShakeKey : len err\r\n%s\r\n%s\r\n%s\r\n", myKey, tempKey, acceptKey);
  652.  
    return -1;
  653.  
    }
  654.  
    else if(strcmp((const char *)tempKey, (const char *)acceptKey) != 0)
  655.  
    {
  656.  
    printf("webSocket_matchShakeKey : str err\r\n%s\r\n%s\r\n", tempKey, acceptKey);
  657.  
    return -1;
  658.  
    }
  659.  
    return 0;
  660.  
    }
  661.  
    /*******************************************************************************
  662.  
    * 名称: webSocket_buildHttpHead
  663.  
    * 功能: 构建client端连接服务器时的http协议头, 注意websocket是GET形式的
  664.  
    * 形参: *ip:要连接的服务器ip字符串
  665.  
    * port : 服务器端口
  666.  
    * *interfacePath : 要连接的端口地址
  667.  
    * *shakeKey : 握手key, 可以由任意的16位字符串打包成base64后得到
  668.  
    * *package : 存储最后打包好的内容
  669.  
    * 返回: 无
  670.  
    * 说明: 无
  671.  
    ******************************************************************************/
  672.  
    void webSocket_buildHttpHead(char *ip, int port, char *interfacePath, unsigned char *shakeKey, char *package)
  673.  
    {
  674.  
    const char httpDemo[] = "GET %s HTTP/1.1\r\n"
  675.  
    "Connection: Upgrade\r\n"
  676.  
    "Host: %s:%d\r\n"
  677.  
    "Sec-WebSocket-Key: %s\r\n"
  678.  
    "Sec-WebSocket-Version: 13\r\n"
  679.  
    "Upgrade: websocket\r\n\r\n";
  680.  
    sprintf(package, httpDemo, interfacePath, ip, port, shakeKey);
  681.  
    }
  682.  
    /*******************************************************************************
  683.  
    * 名称: webSocket_buildHttpRespond
  684.  
    * 功能: 构建server端回复client连接请求的http协议
  685.  
    * 形参: *acceptKey:来自client的握手key
  686.  
    * acceptKeyLen : 长度
  687.  
    * *package : 存储
  688.  
    * 返回: 无
  689.  
    * 说明: 无
  690.  
    ******************************************************************************/
  691.  
    void webSocket_buildHttpRespond(unsigned char *acceptKey, unsigned int acceptKeyLen, char *package)
  692.  
    {
  693.  
    const char httpDemo[] = "HTTP/1.1 101 Switching Protocols\r\n"
  694.  
    "Upgrade: websocket\r\n"
  695.  
    "Server: Microsoft-HTTPAPI/2.0\r\n"
  696.  
    "Connection: Upgrade\r\n"
  697.  
    "Sec-WebSocket-Accept: %s\r\n"
  698.  
    "%s\r\n\r\n"; // 时间打包待续 // 格式如 "Date: Tue, 20 Jun 2017 08:50:41 CST\r\n"
  699.  
    time_t now;
  700.  
    struct tm *tm_now;
  701.  
    char timeStr[256] = {0};
  702.  
    unsigned char respondShakeKey[256] = {0};
  703.  
    // 构建回应的握手key
  704.  
    webSocket_buildRespondShakeKey(acceptKey, acceptKeyLen, respondShakeKey);
  705.  
    // 构建回应时间字符串
  706.  
    time(&now);
  707.  
    tm_now = localtime(&now);
  708.  
    strftime(timeStr, sizeof(timeStr), "Date: %a, %d %b %Y %T %Z", tm_now);
  709.  
    // 组成回复信息
  710.  
    sprintf(package, httpDemo, respondShakeKey, timeStr);
  711.  
    }
  712.  
    /*******************************************************************************
  713.  
    * 名称: webSocket_enPackage
  714.  
    * 功能: websocket数据收发阶段的数据打包, 通常client发server的数据都要isMask(掩码)处理, 反之server到client却不用
  715.  
    * 形参: *data:准备发出的数据
  716.  
    * dataLen : 长度
  717.  
    * *package : 打包后存储地址
  718.  
    * packageMaxLen : 存储地址可用长度
  719.  
    * isMask : 是否使用掩码 1要 0 不要
  720.  
    * type : 数据类型, 由打包后第一个字节决定, 这里默认是数据传输, 即0x81
  721.  
    * 返回: 打包后的长度(会比原数据长2~16个字节不等) <=0 打包失败
  722.  
    * 说明: 无
  723.  
    ******************************************************************************/
  724.  
    int webSocket_enPackage(unsigned char *data, unsigned int dataLen, unsigned char *package, unsigned int packageMaxLen, bool isMask, WebsocketData_Type type)
  725.  
    {
  726.  
    unsigned char maskKey[4] = {0}; // 掩码
  727.  
    unsigned char temp1, temp2;
  728.  
    int count;
  729.  
    unsigned int i, len = 0;
  730.  
     
  731.  
    if(packageMaxLen < 2)
  732.  
    return -1;
  733.  
     
  734.  
    if(type == WDT_MINDATA)
  735.  
    *package++ = 0x00;
  736.  
    else if(type == WDT_TXTDATA)
  737.  
    *package++ = 0x81;
  738.  
    else if(type == WDT_BINDATA)
  739.  
    *package++ = 0x82;
  740.  
    else if(type == WDT_DISCONN)
  741.  
    *package++ = 0x88;
  742.  
    else if(type == WDT_PING)
  743.  
    *package++ = 0x89;
  744.  
    else if(type == WDT_PONG)
  745.  
    *package++ = 0x8A;
  746.  
    else if(type == 100)
  747.  
    *package++ = 0x02;//add by cheyang//return -1;
  748.  
    else if(type == 99)
  749.  
    *package++ = 0x80;//add by cheyang//return -1;
  750.  
     
  751.  
    //
  752.  
    if(isMask)
  753.  
    *package = 0x80;
  754.  
    len += 1;
  755.  
    //
  756.  
    if(dataLen < 126)
  757.  
    {
  758.  
    *package++ |= (dataLen&0x7F);
  759.  
    len += 1;
  760.  
    }
  761.  
    else if(dataLen < 65536)
  762.  
    {
  763.  
    if(packageMaxLen < 4)
  764.  
    return -1;
  765.  
    *package++ |= 0x7E;
  766.  
    *package++ = (char)((dataLen >> 8) & 0xFF);
  767.  
    *package++ = (unsigned char)((dataLen >> 0) & 0xFF);
  768.  
    len += 3;
  769.  
    }
  770.  
    else if(dataLen < 0xFFFFFFFF)
  771.  
    {
  772.  
    if(packageMaxLen < 10)
  773.  
    return -1;
  774.  
    *package++ |= 0x7F;
  775.  
    *package++ = 0; //(char)((dataLen >> 56) & 0xFF); // 数据长度变量是 unsigned int dataLen, 暂时没有那么多数据
  776.  
    *package++ = 0; //(char)((dataLen >> 48) & 0xFF);
  777.  
    *package++ = 0; //(char)((dataLen >> 40) & 0xFF);
  778.  
    *package++ = 0; //(char)((dataLen >> 32) & 0xFF);
  779.  
    *package++ = (char)((dataLen >> 24) & 0xFF); // 到这里就够传4GB数据了
  780.  
    *package++ = (char)((dataLen >> 16) & 0xFF);
  781.  
    *package++ = (char)((dataLen >> 8) & 0xFF);
  782.  
    *package++ = (char)((dataLen >> 0) & 0xFF);
  783.  
    len += 9;
  784.  
    }
  785.  
    //
  786.  
    if(isMask) // 数据使用掩码时, 使用异或解码, maskKey[4]依次和数据异或运算, 逻辑如下
  787.  
    {
  788.  
    if(packageMaxLen < len + dataLen + 4)
  789.  
    return -1;
  790.  
    webSocket_getRandomString(maskKey, sizeof(maskKey)); // 随机生成掩码
  791.  
    *package++ = maskKey[0];
  792.  
    *package++ = maskKey[1];
  793.  
    *package++ = maskKey[2];
  794.  
    *package++ = maskKey[3];
  795.  
    len += 4;
  796.  
    if(type == WDT_TXTDATA){
  797.  
    printf("the key is %d,%d,%d,%d.\n",maskKey[0],maskKey[1],maskKey[2],maskKey[3]);
  798.  
    }
  799.  
    for(i = 0, count = 0; i < dataLen; i++)
  800.  
    {
  801.  
    temp1 = maskKey[count];
  802.  
    temp2 = data[i];
  803.  
    if(type == WDT_TXTDATA){
  804.  
    printf("the file name is %d,key:%d,\n",temp2,maskKey[count]);
  805.  
    }
  806.  
    *package++ = (char)(((~temp1)&temp2) | (temp1&(~temp2))); // 异或运算后得到数据
  807.  
    if(type == WDT_TXTDATA){
  808.  
    printf("after key name is %d,\n",(char)(((~temp1)&temp2) | (temp1&(~temp2))));
  809.  
    }
  810.  
    count += 1;
  811.  
    if(count >= sizeof(maskKey)) // maskKey[4]循环使用
  812.  
    count = 0;
  813.  
    }
  814.  
    len += i;
  815.  
    *package = '\0';
  816.  
    }
  817.  
    else // 数据没使用掩码, 直接复制数据段
  818.  
    {
  819.  
    if(packageMaxLen < len + dataLen)
  820.  
    return -1;
  821.  
    memcpy(package, data, dataLen);
  822.  
    package[dataLen] = '\0';
  823.  
    len += dataLen;
  824.  
    }
  825.  
    //
  826.  
    return len;
  827.  
    }
  828.  
    /*******************************************************************************
  829.  
    * 名称: webSocket_dePackage
  830.  
    * 功能: websocket数据收发阶段的数据解包, 通常client发server的数据都要isMask(掩码)处理, 反之server到client却不用
  831.  
    * 形参: *data:解包的数据
  832.  
    * dataLen : 长度
  833.  
    * *package : 解包后存储地址
  834.  
    * packageMaxLen : 存储地址可用长度
  835.  
    * *packageLen : 解包所得长度
  836.  
    * 返回: 解包识别的数据类型 如 : txt数据, bin数据, ping, pong等
  837.  
    * 说明: 无
  838.  
    ******************************************************************************/
  839.  
    int webSocket_dePackage(unsigned char *data, unsigned int dataLen, unsigned char *package, unsigned int packageMaxLen, unsigned int *packageLen, unsigned int *packageHeadLen)
  840.  
    {
  841.  
    unsigned char maskKey[4] = {0}; // 掩码
  842.  
    unsigned char temp1, temp2;
  843.  
    char Mask = 0, type;
  844.  
    int count, ret;
  845.  
    unsigned int i, len = 0, dataStart = 2;
  846.  
    if(dataLen < 2)
  847.  
    return WDT_ERR;
  848.  
     
  849.  
    type = data[0]&0x0F;
  850.  
     
  851.  
    if((data[0]&0x80) == 0x80)
  852.  
    {
  853.  
    if(type == 0x01)
  854.  
    ret = WDT_TXTDATA;
  855.  
    else if(type == 0x02)
  856.  
    ret = WDT_BINDATA;
  857.  
    else if(type == 0x08)
  858.  
    ret = WDT_DISCONN;
  859.  
    else if(type == 0x09)
  860.  
    ret = WDT_PING;
  861.  
    else if(type == 0x0A)
  862.  
    ret = WDT_PONG;
  863.  
    else
  864.  
    return WDT_ERR;
  865.  
    }
  866.  
    else if(type == 0x00)
  867.  
    ret = WDT_MINDATA;
  868.  
    else
  869.  
    return WDT_ERR;
  870.  
    //
  871.  
    if((data[1] & 0x80) == 0x80)
  872.  
    {
  873.  
    Mask = 1;
  874.  
    count = 4;
  875.  
    }
  876.  
    else
  877.  
    {
  878.  
    Mask = 0;
  879.  
    count = 0;
  880.  
    }
  881.  
    //
  882.  
    len = data[1] & 0x7F;
  883.  
    //
  884.  
    if(len == 126)
  885.  
    {
  886.  
    if(dataLen < 4)
  887.  
    return WDT_ERR;
  888.  
    len = data[2];
  889.  
    len = (len << 8) + data[3];
  890.  
    if(packageLen) *packageLen = len;//转储包长度
  891.  
    if(packageHeadLen) *packageHeadLen = 4 + count;
  892.  
    //
  893.  
    if(dataLen < len + 4 + count)
  894.  
    return WDT_ERR;
  895.  
    if(Mask)
  896.  
    {
  897.  
    maskKey[0] = data[4];
  898.  
    maskKey[1] = data[5];
  899.  
    maskKey[2] = data[6];
  900.  
    maskKey[3] = data[7];
  901.  
    dataStart = 8;
  902.  
    }
  903.  
    else
  904.  
    dataStart = 4;
  905.  
    }
  906.  
    else if(len == 127)
  907.  
    {
  908.  
    if(dataLen < 10)
  909.  
    return WDT_ERR;
  910.  
    if(data[2] != 0 || data[3] != 0 || data[4] != 0 || data[5] != 0) //使用8个字节存储长度时,前4位必须为0,装不下那么多数据...
  911.  
    return WDT_ERR;
  912.  
    len = data[6];
  913.  
    len = (len << 8) + data[7];
  914.  
    len = (len << 8) + data[8];
  915.  
    len = (len << 8) + data[9];
  916.  
    if(packageLen) *packageLen = len;//转储包长度
  917.  
    if(packageHeadLen) *packageHeadLen = 10 + count;
  918.  
    //
  919.  
    if(dataLen < len + 10 + count)
  920.  
    return WDT_ERR;
  921.  
    if(Mask)
  922.  
    {
  923.  
    maskKey[0] = data[10];
  924.  
    maskKey[1] = data[11];
  925.  
    maskKey[2] = data[12];
  926.  
    maskKey[3] = data[13];
  927.  
    dataStart = 14;
  928.  
    }
  929.  
    else
  930.  
    dataStart = 10;
  931.  
    }
  932.  
    else
  933.  
    {
  934.  
    if(packageLen) *packageLen = len;//转储包长度
  935.  
    if(packageHeadLen) *packageHeadLen = 2 + count;
  936.  
    //
  937.  
    if(dataLen < len + 2 + count)
  938.  
    return WDT_ERR;
  939.  
    if(Mask)
  940.  
    {
  941.  
    maskKey[0] = data[2];
  942.  
    maskKey[1] = data[3];
  943.  
    maskKey[2] = data[4];
  944.  
    maskKey[3] = data[5];
  945.  
    dataStart = 6;
  946.  
    }
  947.  
    else
  948.  
    dataStart = 2;
  949.  
    }
  950.  
    //
  951.  
    if(dataLen < len + dataStart)
  952.  
    return WDT_ERR;
  953.  
    //
  954.  
    if(packageMaxLen < len + 1)
  955.  
    return WDT_ERR;
  956.  
    //
  957.  
    if(Mask) // 解包数据使用掩码时, 使用异或解码, maskKey[4]依次和数据异或运算, 逻辑如下
  958.  
    {
  959.  
    for(i = 0, count = 0; i < len; i++)
  960.  
    {
  961.  
    temp1 = maskKey[count];
  962.  
    temp2 = data[i + dataStart];
  963.  
    *package++ = (char)(((~temp1)&temp2) | (temp1&(~temp2))); // 异或运算后得到数据###与接收端"^"运算符结果一样 by cy###
  964.  
    count += 1;
  965.  
    if(count >= sizeof(maskKey)) // maskKey[4]循环使用
  966.  
    count = 0;
  967.  
    }
  968.  
    *package = '\0';
  969.  
    }
  970.  
    else // 解包数据没使用掩码, 直接复制数据段
  971.  
    {
  972.  
    memcpy(package, &data[dataStart], len);
  973.  
    package[len] = '\0';
  974.  
    }
  975.  
    //
  976.  
    return ret;
  977.  
    }/*******************************************************************************
  978.  
    * 名称: webSocket_clientLinkToServer
  979.  
    * 功能: 向websocket服务器发送http(携带握手key), 以和服务器构建连接, 非阻塞模式
  980.  
    * 形参: *ip:服务器ip
  981.  
    * port : 服务器端口
  982.  
    * *interface_path : 接口地址
  983.  
    * 返回: >0 返回连接句柄 <= 0 连接失败或超时, 所花费的时间 ms
  984.  
    * 说明: 无
  985.  
    ******************************************************************************/
  986.  
    int webSocket_clientLinkToServer(char *ip, int port, char *interface_path)
  987.  
    {
  988.  
    int ret, fd , timeOut;
  989.  
    int i;
  990.  
    unsigned char loginBuf[512] = {0}, recBuf[512] = {0}, shakeKey[128] = {0}, *p;
  991.  
    char tempIp[128] = {0};
  992.  
    //服务器端网络地址结构体
  993.  
    struct sockaddr_in report_addr;
  994.  
    memset(&report_addr,0,sizeof(report_addr)); // 数据初始化--清零
  995.  
    report_addr.sin_family = AF_INET; // 设置为IP通信
  996.  
    //report_addr.sin_addr.s_addr = inet_addr(ip);
  997.  
    if((report_addr.sin_addr.s_addr = inet_addr(ip)) == INADDR_NONE) // 服务器IP地址, 自动域名转换
  998.  
    {
  999.  
    ret = websocket_getIpByHostName(ip, tempIp);
  1000.  
    if(ret < 0)
  1001.  
    return ret;
  1002.  
    else if(strlen(tempIp) < 7)
  1003.  
    return -ret;
  1004.  
    else
  1005.  
    timeOut += ret;
  1006.  
    //
  1007.  
    if((report_addr.sin_addr.s_addr = inet_addr(tempIp)) == INADDR_NONE)
  1008.  
    return -ret;
  1009.  
    #ifdef WEBSOCKET_DEBUG
  1010.  
    printf("webSocket_clientLinkToServer : Host(%s) to Ip(%s)\r\n", ip, tempIp);
  1011.  
    #endif
  1012.  
    }
  1013.  
    report_addr.sin_port = htons(port); // 服务器端口号
  1014.  
    //
  1015.  
    //printf("webSocket_clientLinkToServer : ip/%s, port/%d path/%s\r\n", ip, port, interface_path);
  1016.  
    //create unix socket
  1017.  
    if((fd = socket(AF_INET,SOCK_STREAM, 0)) < 0)
  1018.  
    {
  1019.  
    printf("webSocket_login : cannot create socket\r\n");
  1020.  
    return -1;
  1021.  
    }
  1022.  
     
  1023.  
    // 测试 ----- 创建握手key 和 匹配返回key
  1024.  
    // webSocket_buildShakeKey(shakeKey);
  1025.  
    // printf("key1:%s\r\n", shakeKey);
  1026.  
    // webSocket_buildRespondShakeKey(shakeKey, strlen(shakeKey), shakeKey);
  1027.  
    // printf("key2:%s\r\n", shakeKey);
  1028.  
     
  1029.  
    //非阻塞
  1030.  
    ret = fcntl(fd , F_GETFL , 0);
  1031.  
    fcntl(fd , F_SETFL , ret | O_NONBLOCK);
  1032.  
     
  1033.  
    //connect
  1034.  
    timeOut = 0;
  1035.  
    while(connect(fd , (struct sockaddr *)&report_addr,sizeof(struct sockaddr)) == -1)
  1036.  
    {
  1037.  
    if(++timeOut > WEBSOCKET_LOGIN_CONNECT_TIMEOUT)
  1038.  
    {
  1039.  
    printf("webSocket_login : cannot connect to %s:%d ! %d\r\n" , ip, port, timeOut);
  1040.  
    close(fd);
  1041.  
    return -timeOut;
  1042.  
    }
  1043.  
    webSocket_delayms(1); //1ms
  1044.  
    }
  1045.  
     
  1046.  
    //发送http协议头
  1047.  
    memset(shakeKey, 0, sizeof(shakeKey));
  1048.  
    webSocket_buildShakeKey(shakeKey); // 创建握手key
  1049.  
     
  1050.  
    memset(loginBuf, 0, sizeof(loginBuf)); // 创建协议包
  1051.  
    webSocket_buildHttpHead(ip, port, interface_path, shakeKey, (char *)loginBuf);
  1052.  
    //发出协议包
  1053.  
    ret = send(fd , loginBuf , strlen((const char*)loginBuf) , MSG_NOSIGNAL);
  1054.  
     
  1055.  
    //显示http请求
  1056.  
    #ifdef WEBSOCKET_DEBUG
  1057.  
    printf("\r\nconnect : %dms\r\nlogin_send:\r\n%s\r\n" , timeOut, loginBuf);
  1058.  
    #endif
  1059.  
    //
  1060.  
    while(1)
  1061.  
    {
  1062.  
    memset(recBuf , 0 , sizeof(recBuf));
  1063.  
    ret = recv(fd , recBuf , sizeof(recBuf) , MSG_NOSIGNAL);
  1064.  
    if(ret > 0)
  1065.  
    {
  1066.  
    if(strncmp((const char *)recBuf, (const char *)"HTTP", strlen((const char *)"HTTP")) == 0) // 返回的是http回应信息
  1067.  
    {
  1068.  
    //显示http返回
  1069.  
    #ifdef WEBSOCKET_DEBUG
  1070.  
    printf("\r\nlogin_recv : %d / %dms\r\n%s\r\n" , ret, timeOut, recBuf);
  1071.  
    #endif
  1072.  
    //
  1073.  
    if((p = (unsigned char *)strstr((const char *)recBuf, (const char *)"Sec-WebSocket-Accept: ")) != NULL) // 定位到握手字符串
  1074.  
    {
  1075.  
    p += strlen((const char *)"Sec-WebSocket-Accept: ");
  1076.  
    sscanf((const char *)p, "%s\r\n", p);
  1077.  
    if(webSocket_matchShakeKey(shakeKey, strlen((const char *)shakeKey), p, strlen((const char *)p)) == 0) // 比对握手信息
  1078.  
    return fd; // 连接成功, 返回连接句柄fd
  1079.  
    else
  1080.  
    ret = send(fd , loginBuf , strlen((const char*)loginBuf) , MSG_NOSIGNAL); // 握手信号不对, 重发协议包
  1081.  
    }
  1082.  
    else
  1083.  
    ret = send(fd , loginBuf , strlen((const char*)loginBuf) , MSG_NOSIGNAL); // 重发协议包
  1084.  
    }
  1085.  
    // #ifdef WEBSOCKET_DEBUG
  1086.  
    // 显示异常返回数据
  1087.  
    else
  1088.  
    {
  1089.  
    if(recBuf[0] >= ' ' && recBuf[0] <= '~')
  1090.  
    printf("\r\nlogin_recv : %d\r\n%s\r\n" , ret, recBuf);
  1091.  
    else
  1092.  
    {
  1093.  
    printf("\r\nlogin_recv : %d\r\n" , ret);
  1094.  
    for(i = 0; i < ret; i++)
  1095.  
    printf("%.2X ", recBuf[i]);
  1096.  
    printf("\r\n");
  1097.  
    }
  1098.  
    }
  1099.  
    // #endif
  1100.  
    }
  1101.  
    else if(ret <= 0)
  1102.  
    ;
  1103.  
    if(++timeOut > WEBSOCKET_LOGIN_RESPOND_TIMEOUT)
  1104.  
    {
  1105.  
    close(fd);
  1106.  
    return -timeOut;
  1107.  
    }
  1108.  
    webSocket_delayms(1); //1ms
  1109.  
    }
  1110.  
    //
  1111.  
    close(fd);
  1112.  
    return -timeOut;
  1113.  
    }
  1114.  
    /*******************************************************************************
  1115.  
    * 名称: webSocket_serverLinkToClient
  1116.  
    * 功能: 服务器回复客户端的连接请求, 以建立websocket连接
  1117.  
    * 形参: fd:连接句柄
  1118.  
    * *recvBuf : 接收到来自客户端的数据(内含http连接请求)
  1119.  
    * bufLen :
  1120.  
    * 返回: >0 建立websocket连接成功 <=0 建立websocket连接失败
  1121.  
    * 说明: 无
  1122.  
    ******************************************************************************/
  1123.  
    int webSocket_serverLinkToClient(int fd, char *recvBuf, int bufLen)
  1124.  
    {
  1125.  
    char *p;
  1126.  
    int ret;
  1127.  
    char recvShakeKey[512], respondPackage[1024];
  1128.  
    if((p = strstr(recvBuf, "Sec-WebSocket-Key: ")) == NULL)
  1129.  
    return -1;
  1130.  
    p += strlen("Sec-WebSocket-Key: ");
  1131.  
    //
  1132.  
    memset(recvShakeKey, 0, sizeof(recvShakeKey));
  1133.  
    sscanf(p, "%s", recvShakeKey); // 取得握手key
  1134.  
    ret = strlen(recvShakeKey);
  1135.  
    if(ret < 1)
  1136.  
    return -1;
  1137.  
    //
  1138.  
    memset(respondPackage, 0, sizeof(respondPackage));
  1139.  
    webSocket_buildHttpRespond((unsigned char *)recvShakeKey, (unsigned int)ret, respondPackage);
  1140.  
    //
  1141.  
    return send(fd, respondPackage, strlen(respondPackage), MSG_NOSIGNAL);
  1142.  
    }
  1143.  
    /*******************************************************************************
  1144.  
    * 名称: webSocket_send
  1145.  
    * 功能: websocket数据基本打包和发送
  1146.  
    * 形参: fd:连接句柄
  1147.  
    * *data : 数据
  1148.  
    * dataLen : 长度
  1149.  
    * isMask : 数据是否使用掩码, 客户端到服务器必须使用掩码模式
  1150.  
    * type : 数据要要以什么识别头类型发送(txt, bin, ping, pong ...)
  1151.  
    * 返回: 调用send的返回
  1152.  
    * 说明: 无
  1153.  
    ******************************************************************************/
  1154.  
    int webSocket_send(int fd, char *data, int dataLen, bool isMask, WebsocketData_Type type)
  1155.  
    {
  1156.  
    unsigned char *webSocketPackage = NULL;
  1157.  
    int retLen, ret;
  1158.  
    #ifdef WEBSOCKET_DEBUG
  1159.  
    unsigned int i;
  1160.  
    printf("webSocket_send : %d\r\n", dataLen);
  1161.  
    #endif
  1162.  
    //---------- websocket数据打包 ----------
  1163.  
    webSocketPackage = (unsigned char *)calloc(dataLen + 128, sizeof(char));
  1164.  
    retLen = webSocket_enPackage((unsigned char *)data, dataLen, webSocketPackage, (dataLen + 128), isMask, type);
  1165.  
    //显示数据
  1166.  
    #ifdef WEBSOCKET_DEBUG
  1167.  
    printf("webSocket_send : %d\r\n" , retLen);
  1168.  
    for(i = 0; i < retLen; i ++)
  1169.  
    printf("%.2X ", webSocketPackage[i]);
  1170.  
    printf("\r\n");
  1171.  
    #endif
  1172.  
    //
  1173.  
    printf("webSocket_send : %d\r\n" , retLen);
  1174.  
    ret = send(fd, webSocketPackage, retLen, MSG_NOSIGNAL);
  1175.  
    free(webSocketPackage);
  1176.  
    return ret;
  1177.  
    }
  1178.  
    /*******************************************************************************
  1179.  
    * 名称: webSocket_recv
  1180.  
    * 功能: websocket数据接收和基本解包
  1181.  
    * 形参: fd:连接句柄
  1182.  
    * *data : 数据接收地址
  1183.  
    * dataMaxLen : 接收区可用最大长度
  1184.  
    * 返回: = 0 没有收到有效数据 > 0 成功接收并解包数据 < 0 非包数据的长度
  1185.  
    * 说明: 无
  1186.  
    ******************************************************************************/
  1187.  
    int webSocket_recv(int fd, char *data, int dataMaxLen, WebsocketData_Type *dataType)
  1188.  
    {
  1189.  
    unsigned char *webSocketPackage = NULL, *recvBuf = NULL;
  1190.  
    int ret, dpRet = WDT_NULL, retTemp, retFinal = 0;
  1191.  
    int retLen = 0, retHeadLen = 0;
  1192.  
    //
  1193.  
    int timeOut = 0; //续传时,等待下一包需加时间限制
  1194.  
     
  1195.  
    recvBuf = (unsigned char *)calloc(dataMaxLen, sizeof(char));
  1196.  
    ret = recv(fd, recvBuf, dataMaxLen, MSG_NOSIGNAL);
  1197.  
    //数据可能超出了范围限制
  1198.  
    if(ret == dataMaxLen)
  1199.  
    printf("webSocket_recv : warning !! recv buff too large !! (recv/%d)\r\n", ret);
  1200.  
    //
  1201.  
    if(ret > 0)
  1202.  
    {
  1203.  
    //---------- websocket数据解包 ----------
  1204.  
    webSocketPackage = (unsigned char *)calloc(ret + 128, sizeof(char));
  1205.  
    dpRet = webSocket_dePackage(recvBuf, ret, webSocketPackage, (ret + 128), (unsigned int *)&retLen, (unsigned int *)&retHeadLen);
  1206.  
    if(dpRet == WDT_ERR && retLen == 0) //非包数据
  1207.  
    {
  1208.  
    memset(data, 0, dataMaxLen);
  1209.  
    if(ret < dataMaxLen)
  1210.  
    {
  1211.  
    memcpy(data, recvBuf, ret);
  1212.  
    retFinal = -ret;
  1213.  
    }
  1214.  
    else
  1215.  
    {
  1216.  
    memcpy(data, recvBuf, dataMaxLen);
  1217.  
    retFinal = -dataMaxLen;
  1218.  
    }
  1219.  
    }
  1220.  
    else //正常收包
  1221.  
    {
  1222.  
    //数据可能超出了范围限制
  1223.  
    if(retLen > dataMaxLen)
  1224.  
    {
  1225.  
    printf("webSocket_recv : warning !! recv package too large !! (recvPackage/%d)\r\n", retLen);
  1226.  
    goto recv_return_null;
  1227.  
    }
  1228.  
    //显示数据包的头10个字节
  1229.  
    #ifdef WEBSOCKET_DEBUG
  1230.  
    if(ret > 10)
  1231.  
    printf("webSocket_recv : ret/%d, dpRet/%d, retLen/%d, head/%d : %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X\r\n",
  1232.  
    ret, dpRet, retLen, retHeadLen,
  1233.  
    recvBuf[0], recvBuf[1], recvBuf[2], recvBuf[3], recvBuf[4],
  1234.  
    recvBuf[5], recvBuf[6], recvBuf[7], recvBuf[8], recvBuf[9]);
  1235.  
    #endif
  1236.  
     
  1237.  
    //续传? 检查数据包的头10个字节发现recv()时并没有把一包数据接收完,继续接收..
  1238.  
    if(ret < retHeadLen + retLen)
  1239.  
    {
  1240.  
    timeOut = 50;//50*10=500ms等待
  1241.  
    while(ret < retHeadLen + retLen)
  1242.  
    {
  1243.  
    webSocket_delayms(10);
  1244.  
    retTemp = recv(fd, &recvBuf[ret], dataMaxLen - ret, MSG_NOSIGNAL);
  1245.  
    if(retTemp > 0){
  1246.  
    timeOut = 50;//50*10=500ms等待
  1247.  
    ret += retTemp;
  1248.  
    }else{
  1249.  
    if(errno == EAGAIN || errno == EINTR);//连接中断
  1250.  
    else goto recv_return_null;
  1251.  
    }
  1252.  
    if(--timeOut < 1)
  1253.  
    goto recv_return_null;
  1254.  
    }
  1255.  
    //再解包一次
  1256.  
    free(webSocketPackage);
  1257.  
    webSocketPackage = (unsigned char *)calloc(ret + 128, sizeof(char));
  1258.  
    dpRet = webSocket_dePackage(recvBuf, ret, webSocketPackage, (ret + 128), (unsigned int *)&retLen, (unsigned int *)&retHeadLen);
  1259.  
    //
  1260.  
    if(ret > 10)
  1261.  
    printf("webSocket_recv : ret/%d, dpRet/%d, retLen/%d, head/%d : %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X\r\n",
  1262.  
    ret, dpRet, retLen, retHeadLen,
  1263.  
    recvBuf[0], recvBuf[1], recvBuf[2], recvBuf[3], recvBuf[4],
  1264.  
    recvBuf[5], recvBuf[6], recvBuf[7], recvBuf[8], recvBuf[9]);
  1265.  
    }
  1266.  
    //
  1267.  
    if(retLen > 0)
  1268.  
    {
  1269.  
    if(dpRet == WDT_PING)
  1270.  
    {
  1271.  
    webSocket_send(fd, (char *)webSocketPackage, retLen, true, WDT_PONG);//自动 ping-pong
  1272.  
    // 显示数据
  1273.  
    printf("webSocket_recv : PING %d\r\n%s\r\n" , retLen, webSocketPackage);
  1274.  
    }
  1275.  
    else if(dpRet == WDT_PONG)
  1276.  
    {
  1277.  
    printf("webSocket_recv : PONG %d\r\n%s\r\n" , retLen, webSocketPackage);
  1278.  
    }
  1279.  
    else //if(dpRet == WDT_TXTDATA || dpRet == WDT_BINDATA || dpRet == WDT_MINDATA)
  1280.  
    {
  1281.  
    memcpy(data, webSocketPackage, retLen);
  1282.  
    // 显示数据
  1283.  
    #ifdef WEBSOCKET_DEBUG
  1284.  
    if(webSocketPackage[0] >= ' ' && webSocketPackage[0] <= '~')
  1285.  
    printf("\r\nwebSocket_recv : New Package StrFile dpRet:%d/retLen:%d\r\n%s\r\n" , dpRet, retLen, webSocketPackage);
  1286.  
    else
  1287.  
    {
  1288.  
    printf("\r\nwebSocket_recv : New Package BinFile dpRet:%d/retLen:%d\r\n" , dpRet, retLen);
  1289.  
    int i;
  1290.  
    for(i = 0; i < retLen; i++)
  1291.  
    printf("%.2X ", webSocketPackage[i]);
  1292.  
    printf("\r\n");
  1293.  
    }
  1294.  
    #endif
  1295.  
    }
  1296.  
    //
  1297.  
    retFinal = retLen;
  1298.  
    }
  1299.  
    #ifdef WEBSOCKET_DEBUG
  1300.  
    else
  1301.  
    {
  1302.  
    // 显示数据
  1303.  
    if(recvBuf[0] >= ' ' && recvBuf[0] <= '~')
  1304.  
    printf("\r\nwebSocket_recv : ret:%d/dpRet:%d/retLen:%d\r\n%s\r\n" , ret, dpRet, retLen, recvBuf);
  1305.  
    else
  1306.  
    {
  1307.  
    printf("\r\nwebSocket_recv : ret:%d/dpRet:%d/retLen:%d\r\n%s\r\n" , ret, dpRet, retLen, recvBuf);
  1308.  
    int i;
  1309.  
    for(i = 0; i < ret; i++)
  1310.  
    printf("%.2X ", recvBuf[i]);
  1311.  
    printf("\r\n");
  1312.  
    }
  1313.  
    }
  1314.  
    #endif
  1315.  
    }
  1316.  
    }
  1317.  
     
  1318.  
    if(recvBuf) free(recvBuf);
  1319.  
    if(webSocketPackage) free(webSocketPackage);
  1320.  
    if(dataType) *dataType = dpRet;
  1321.  
    return retFinal;
  1322.  
     
  1323.  
    recv_return_null:
  1324.  
     
  1325.  
    if(recvBuf) free(recvBuf);
  1326.  
    if(webSocketPackage) free(webSocketPackage);
  1327.  
    if(dataType) *dataType = dpRet;
  1328.  
    return 0;
  1329.  
    }
  1330.  
     
  1331.  
    int main(void)
  1332.  
    {
  1333.  
    int ret, timeCount = 0;
  1334.  
    int fd;
  1335.  
    char buff[10240];
  1336.  
    int pid;
  1337.  
    //
  1338.  
    pid = getpid();
  1339.  
    printf("\r\n========== client(%d) start ! ==========\r\n\r\n", pid);
  1340.  
    //
  1341.  
    //netCheck_getIP("eth0", ip);
  1342.  
    printf("\r\n========== ip(%s) port(%d) ! ==========\r\n\r\n", ip,port);
  1343.  
    if((fd = webSocket_clientLinkToServer(ip, port, "/null")) <= 0)
  1344.  
    {
  1345.  
    printf("client link to server failed !\r\n");
  1346.  
    return -1;
  1347.  
    }
  1348.  
    webSocket_delayms(100);
  1349.  
    //
  1350.  
    memset(buff, 0, sizeof(buff));
  1351.  
    sprintf(buff, "tts1.pcm");
  1352.  
    webSocket_send(fd, buff, strlen(buff), true, WDT_TXTDATA);
  1353.  
    FILE * fid = fopen(buff,"r");
  1354.  
    if(fid == NULL)
  1355.  
    {
  1356.  
    printf("打开%s失败","tts1.pcm");
  1357.  
    return;
  1358.  
    }
  1359.  
    //
  1360.  
    char line[1024*3];
  1361.  
    int read_len = 0;
  1362.  
    int rea_size = 0;
  1363.  
    do
  1364.  
    {
  1365.  
     
  1366.  
    read_len = 0;
  1367.  
    memset(line,0,1024);
  1368.  
    int file_size = 0;
  1369.  
    //获取文件大小
  1370.  
    fseek (fid , 0 , SEEK_END);
  1371.  
    long lSize = ftell (fid);
  1372.  
    rewind (fid);
  1373.  
    printf("file lSize %d\n", lSize); //输出
  1374.  
    bool blastMsg = false;
  1375.  
    while(lSize > file_size )
  1376.  
    {
  1377.  
    if(lSize -file_size < 1024*2 ){
  1378.  
     
  1379.  
    read_len = lSize -file_size;
  1380.  
    blastMsg = true;
  1381.  
    printf("get last zhen size:%d\n",read_len);
  1382.  
    }
  1383.  
    else
  1384.  
    {
  1385.  
    read_len = 1024*2;
  1386.  
    }
  1387.  
     
  1388.  
    rea_size = fread(line,sizeof(char),read_len,fid);
  1389.  
    //read_len = fgets(line,1024*2,fid);
  1390.  
    printf("file size :%d;read size :%d\n",file_size, rea_size); //输出
  1391.  
    sleep(1);
  1392.  
    if(file_size == 0){
  1393.  
    ret = webSocket_send(fd, line, rea_size, true, 100);
  1394.  
    }
  1395.  
    else if(blastMsg){
  1396.  
    printf("send last websocket msg :strlen%d;read size :%d\n",strlen(line), rea_size); //输出
  1397.  
    ret = webSocket_send(fd, line, rea_size, false, 99);
  1398.  
     
  1399.  
    }
  1400.  
    else{
  1401.  
    ret = webSocket_send(fd, line, rea_size, false, WDT_MINDATA);
  1402.  
    }
  1403.  
    //strcpy(buff, "123");//即使ping包也要带点数据
  1404.  
    // webSocket_send(fd,buff , strlen(buff), true, WDT_TXTDATA);
  1405.  
     
  1406.  
    file_size += rea_size;
  1407.  
    if(ret > 0)
  1408.  
    {
  1409.  
    printf("client(%d) send : %d\r\n", pid, file_size);
  1410.  
    }
  1411.  
    else // 检查错误, 是否连接已断开
  1412.  
    {
  1413.  
    printf("client() send failure.\r\n");
  1414.  
    if(errno == EAGAIN || errno == EINTR)
  1415.  
    ;
  1416.  
    else
  1417.  
    {
  1418.  
    close(fd);
  1419.  
    break;
  1420.  
    }
  1421.  
    }
  1422.  
    }
  1423.  
    fclose(fid);
  1424.  
    //
  1425.  
    /*memset(buff, 0, sizeof(buff));
  1426.  
    ret = webSocket_recv(fd, buff, sizeof(buff), NULL);
  1427.  
    if(ret > 0)
  1428.  
    {
  1429.  
    //===== 与服务器的应答 =====
  1430.  
    printf("client(%d) recv : %s\r\n", pid, buff);
  1431.  
    //
  1432.  
    if(strstr(buff, "Hi~") != NULL)
  1433.  
    {
  1434.  
    memset(buff, 0, sizeof(buff));
  1435.  
    sprintf(buff, "I am client(%d)", pid);
  1436.  
    ret = webSocket_send(fd, buff, strlen(buff), true, WDT_TXTDATA);
  1437.  
    }
  1438.  
    else
  1439.  
    ;
  1440.  
    // ......
  1441.  
    // ...
  1442.  
     
  1443.  
    // send返回异常, 连接已断开
  1444.  
    if(ret <= 0)
  1445.  
    {
  1446.  
    close(fd);
  1447.  
    break;
  1448.  
    }
  1449.  
    }
  1450.  
    else // 检查错误, 是否连接已断开
  1451.  
    {
  1452.  
    if(errno == EAGAIN || errno == EINTR)
  1453.  
    ;
  1454.  
    else
  1455.  
    {
  1456.  
    close(fd);
  1457.  
    break;
  1458.  
    }
  1459.  
    }*/
  1460.  
     
  1461.  
    //===== 3s客户端心跳 =====
  1462.  
    if(timeCount > 3000)
  1463.  
    {
  1464.  
    timeCount = 10;
  1465.  
    //
  1466.  
    memset(buff, 0, sizeof(buff));
  1467.  
     
  1468.  
    // sprintf(buff, "heart from client(%d)", pid);
  1469.  
    // ret = webSocket_send(fd, buff, strlen(buff), true, WDT_TXTDATA);
  1470.  
     
  1471.  
    strcpy(buff, "123");//即使ping包也要带点数据
  1472.  
    ret = webSocket_send(fd, buff, strlen(buff), true, WDT_PING); //使用ping包代替心跳
  1473.  
     
  1474.  
    if(ret <= 0)
  1475.  
    {
  1476.  
    close(fd);
  1477.  
    break;
  1478.  
    }
  1479.  
    }
  1480.  
    else
  1481.  
    timeCount += 10;
  1482.  
     
  1483.  
    //
  1484.  
    webSocket_delayms(10);
  1485.  
    }while(0);
  1486.  
    printf("client close !\r\n");
  1487.  
    return 0;
  1488.  
    }

从程序可以看到,发送端在发送数据前首先给待发送数据添加了websocket协议首部,数据进行了异或掩码处理。

接收端在收到这个数据之后,首先需要读取首部解析,拿到实际帧数据长度,然后再继续读取数据,并判断数据满帧时,开始解析数据,即实现了组包和拆包的操作。不论客户端消息时满帧、粘包、拆包场景,服务端只有读取数据大于满帧时,在解析数据;如果数据未解析完,那剩余的数据则时下一帧数据,重复判断数据是否满帧。

程序如下:

  1.  
    #include <unistd.h>
  2.  
    #include "websocket_handler.h"
  3.  
    #include <stdio.h>
  4.  
    #include <string.h>
  5.  
    #define DEBUG_LOG printf
  6.  
    #define BUFFLEN 2048
  7.  
     
  8.  
    Websocket_Handler::Websocket_Handler(int fd):
  9.  
    buff_(),
  10.  
    status_(WEBSOCKET_UNCONNECT),
  11.  
    header_map_(),
  12.  
    fd_(fd),
  13.  
    request_(new Websocket_Request),
  14.  
    buff_len(0),
  15.  
    handle(NULL)
  16.  
    {
  17.  
    //channel->setReadhandler(bind(&Http_conn::parse,this));
  18.  
    }
  19.  
    Websocket_Handler::Websocket_Handler(int fd, SP_Channel Channel):
  20.  
    buff_(),
  21.  
    status_(WEBSOCKET_UNCONNECT),
  22.  
    header_map_(),
  23.  
    fd_(fd),
  24.  
    request_(new Websocket_Request),
  25.  
    channel(Channel),
  26.  
    buff_out(),
  27.  
    buff_len(0),
  28.  
    handle(NULL),
  29.  
    m_nOffset(0),
  30.  
    buff_cache()
  31.  
    {
  32.  
    channel->setReadhandler(bind(&Websocket_Handler::handlerconn,this));
  33.  
    }
  34.  
     
  35.  
    Websocket_Handler::~Websocket_Handler(){
  36.  
    //add by cy
  37.  
    delete request_;
  38.  
    }
  39.  
     
  40.  
    void inverted_string(char *str,int len)
  41.  
    {
  42.  
    int i; char temp;
  43.  
    for (i=0;i<len/2;++i)
  44.  
    {
  45.  
    temp = *(str+i);
  46.  
    *(str+i) = *(str+len-i-1);
  47.  
    *(str+len-i-1) = temp;
  48.  
    }
  49.  
    }
  50.  
     
  51.  
     
  52.  
    int Websocket_Handler::recv_request()
  53.  
    {
  54.  
    printf("Websocket_Handler::recv_request: recv request logic.\n");
  55.  
     
  56.  
    char readCache[1024*4] = {0};
  57.  
    int recvsize;
  58.  
    int head_len = 0;
  59.  
     
  60.  
    do{
  61.  
    recvsize = 0;
  62.  
    recvsize = read(fd_,readCache,BUFFLEN);
  63.  
    printf("read:size:%d,curslot:%d.\n",recvsize,m_nOffset);
  64.  
     
  65.  
    if (recvsize < 0)
  66.  
    {
  67.  
    memset(readCache, 0, sizeof(readCache));
  68.  
    printf("read failure,wait next frame websocket.\n");
  69.  
    return 0;
  70.  
    }else if( 0 == recvsize ){
  71.  
    if( NULL != handle ){
  72.  
    fclose(handle);
  73.  
    }
  74.  
    channel->setDeleted(true);
  75.  
    channel->getLoop().lock()->addTimer(channel,0);
  76.  
    return 0;
  77.  
    }
  78.  
     
  79.  
     
  80.  
     
  81.  
    memcpy(buff_+m_nOffset, readCache, recvsize);
  82.  
    m_nOffset = m_nOffset + recvsize;//set offset
  83.  
     
  84.  
    //获取消息头
  85.  
    if( 0 > (head_len = getFrameHeaderInfo(buff_,&header_msg,m_nOffset)) )
  86.  
    {
  87.  
    printf("error is not full frame.\n");
  88.  
    continue;
  89.  
     
  90.  
    }
  91.  
    printf("read frame head\tFIN: %d\tOPCODE: %d\tMASK: %d\tPAYLOADLEN: %d\tHeadlen:%d\n.",
  92.  
    header_msg.fin, header_msg.opcode, header_msg.mask, header_msg.payload_length,head_len);
  93.  
    //读取满帧数据校验
  94.  
    if(header_msg.payload_length > m_nOffset- head_len || header_msg.payload_length <= 0 )
  95.  
    {
  96.  
    continue;
  97.  
    }
  98.  
     
  99.  
    if( 1 ==header_msg.mask){
  100.  
    umask(buff_+head_len,header_msg.payload_length,header_msg.masking_key);
  101.  
    }
  102.  
     
  103.  
    switch(header_msg.opcode){
  104.  
    case 0x00:
  105.  
    printf("recv mid frame.\n");
  106.  
    break;
  107.  
    case 0x01:
  108.  
    {
  109.  
    printf("recv text frame.\n\t%s\n",(buff_+head_len));
  110.  
    if( handle == NULL && header_msg.payload_length <= 1000){
  111.  
    char filename[1024];
  112.  
    sprintf(filename,"./snOfflineVoice_%s.snv",buff_+head_len);
  113.  
    handle = fopen(filename,"a+");
  114.  
    }
  115.  
     
  116.  
    m_nOffset = m_nOffset - header_msg.payload_length - head_len;
  117.  
     
  118.  
    char buffer[2048*2] = {0};
  119.  
    memcpy(buffer, buff_+header_msg.payload_length+head_len,m_nOffset);
  120.  
    memset(buff_,0,BUFFLEN*2);
  121.  
    memcpy(buff_, buffer,m_nOffset);
  122.  
     
  123.  
    return 0;
  124.  
    }
  125.  
    case 0x02:
  126.  
    printf("recv bin frame.\n");
  127.  
    if( handle == NULL){
  128.  
    char filename[1024];
  129.  
    sprintf(filename,"./snOfflineVoice_%02d.snv",header_msg.payload_length);
  130.  
    handle = fopen(filename,"a+");
  131.  
    }
  132.  
    break;
  133.  
    case 0x08:
  134.  
    channel->setDeleted(true);
  135.  
    channel->getLoop().lock()->addTimer(channel,0);
  136.  
    return 0;
  137.  
    case 0x09:
  138.  
    printf("recv ping frame,need send pong frame.\n");
  139.  
    //webSocket_send(fd, (char *)webSocketPackage, retLen, true, WDT_PONG);//自动 ping-pong
  140.  
    return 0;
  141.  
    case 0x0A:
  142.  
    printf("recv pong frame.\n");
  143.  
    return 0;
  144.  
    default:
  145.  
    printf("recv unknow frame.\n");
  146.  
     
  147.  
    }
  148.  
     
  149.  
    //just one frame or frist of mutl_frame
  150.  
    /*if( (1 ==header_msg.fin && 0 < header_msg.opcode && 3 > header_msg.opcode && handle != NULL )
  151.  
    || (0 ==header_msg.fin && 0 !=header_msg.opcode && 3 > header_msg.opcode ) ){
  152.  
    char filename[1024];
  153.  
    sprintf(filename,"./snOfflineVoice_%02d.snv",header_msg.payload_length);
  154.  
     
  155.  
    handle = fopen(filename,"a+");
  156.  
    if(NULL != handle){
  157.  
    fwrite(buff_+head_len, sizeof(char), header_msg.payload_length, handle);
  158.  
    fflush(handle);
  159.  
    printf("fwrite:size:%d,payload_len:%d.\n",header_msg.payload_length,header_msg.payload_length);
  160.  
     
  161.  
    m_nOffset = m_nOffset - header_msg.payload_length - head_len;
  162.  
    char swap[2048] = {0};
  163.  
    memcpy(swap, buff_+header_msg.payload_length+head_len,m_nOffset);
  164.  
    memset(buff_,0,BUFFLEN*2);
  165.  
    memcpy(buff_, swap,m_nOffset);
  166.  
    return 0;//break function
  167.  
    }
  168.  
    }*/
  169.  
     
  170.  
     
  171.  
    if( NULL != handle){
  172.  
     
  173.  
     
  174.  
    fwrite(buff_+head_len, sizeof(char), header_msg.payload_length, handle);
  175.  
    fflush(handle);
  176.  
    m_nOffset = m_nOffset - header_msg.payload_length - head_len;
  177.  
    char swap[2048*2] = {0};
  178.  
    memcpy(swap, buff_+header_msg.payload_length+head_len,m_nOffset);
  179.  
    memset(buff_,0,BUFFLEN*2);
  180.  
    memcpy(buff_, swap,m_nOffset);
  181.  
    printf("fwrite:size:%d,m_nOffset:%d.\n",header_msg.payload_length, m_nOffset);
  182.  
    }
  183.  
     
  184.  
    if(m_nOffset > 4){
  185.  
    memset(&header_msg,0,sizeof(header_msg));
  186.  
    printf(">>>>>>>>>>check Incomming data frame<<<<<<<<<.\n");
  187.  
    if( 0 > (head_len = getFrameHeaderInfo(buff_,&header_msg,m_nOffset)) )
  188.  
    {
  189.  
    printf("error is not full frame.\n");
  190.  
    continue;
  191.  
     
  192.  
    }
  193.  
     
  194.  
    if(header_msg.payload_length <= m_nOffset- head_len&& header_msg.payload_length > 0 )
  195.  
    {
  196.  
    printf("read frame head\tFIN: %d\tOPCODE: %d\tMASK: %d\tPAYLOADLEN: %d\tHeadlen:%d.\n",
  197.  
    header_msg.fin, header_msg.opcode, header_msg.mask, header_msg.payload_length,head_len);
  198.  
     
  199.  
    if( 1 ==header_msg.mask){
  200.  
    umask(buff_+head_len,header_msg.payload_length,header_msg.masking_key);
  201.  
    }
  202.  
     
  203.  
    fwrite(buff_+head_len, sizeof(char), header_msg.payload_length, handle);
  204.  
    fflush(handle);
  205.  
    printf("fwrite more frame:size:%d,m_nOffset:%d.\n",header_msg.payload_length, m_nOffset);
  206.  
    m_nOffset = m_nOffset -header_msg.payload_length-head_len;
  207.  
    char swap[2018] = {0};
  208.  
    memcpy(swap, buff_+header_msg.payload_length+head_len,m_nOffset);
  209.  
    memset(buff_,0,BUFFLEN*2);
  210.  
    memcpy(buff_, swap,m_nOffset);
  211.  
     
  212.  
    }
  213.  
    else{
  214.  
    printf(" Lack of data, need read more data.\n");
  215.  
    continue;
  216.  
    }
  217.  
     
  218.  
    }
  219.  
     
  220.  
     
  221.  
     
  222.  
    if(1 == header_msg.fin && NULL != handle &&
  223.  
    ( 0 == header_msg.opcode || 2 == header_msg.opcode) ){
  224.  
    fclose(handle);
  225.  
    handle = NULL;
  226.  
    m_nOffset = 0;
  227.  
    memset(buff_,0,BUFFLEN*2);
  228.  
    printf("is last frame, need close file.\n");
  229.  
    return 0;
  230.  
    }
  231.  
     
  232.  
    printf("read data again.\n");
  233.  
    }while(1);
  234.  
     
  235.  
    printf("wait next request websocket .\n");
  236.  
     
  237.  
    return 0;
  238.  
    }
  239.  
     
  240.  
    int Websocket_Handler::getFrameHeaderInfo(char *buff,frame_head* head,int curSize)
  241.  
    {
  242.  
    char one_char;
  243.  
    int head_len = 0;
  244.  
     
  245.  
    one_char = buff[0];
  246.  
    head->fin = (one_char & 0x80) == 0x80;
  247.  
    head->opcode = one_char & 0x0F;
  248.  
     
  249.  
     
  250.  
    one_char = buff[1];
  251.  
    head->mask = (one_char & 0x80) == 0X80;
  252.  
     
  253.  
    /*get payload length*/
  254.  
    head->payload_length = one_char & 0x7F;
  255.  
     
  256.  
    if (head->payload_length == 126)
  257.  
    {
  258.  
    char extern_len[2];
  259.  
    extern_len[0] = buff[2];
  260.  
    extern_len[1] = buff[3];
  261.  
     
  262.  
    head->payload_length = (extern_len[0]&0xFF) << 8 | (extern_len[1]&0xFF);
  263.  
    head_len = 4;
  264.  
    }
  265.  
    else if (head->payload_length == 127)
  266.  
    {
  267.  
    char extern_len[8];
  268.  
    //wait to doing
  269.  
    //...
  270.  
    inverted_string(extern_len,8);
  271.  
    memcpy(&(head->payload_length),extern_len,8);
  272.  
    head_len = 10;
  273.  
    }
  274.  
    else if(head->payload_length == 0)
  275.  
    {
  276.  
    printf("read payload_length is 0,close connect.");
  277.  
    return -1;
  278.  
    }
  279.  
    else if(head->payload_length < 126)
  280.  
    {
  281.  
    printf("read payload_length is less 126, is little frame.\n");
  282.  
    head_len = 2;
  283.  
    }
  284.  
     
  285.  
     
  286.  
     
  287.  
    if(head->mask ==1 ){
  288.  
     
  289.  
    if(curSize <= 7 )
  290.  
    {
  291.  
    printf("check buff size error.\n");
  292.  
    return -1;
  293.  
    }
  294.  
    head->masking_key[0] = buff[head_len+0];
  295.  
    head->masking_key[1] = buff[head_len+1];
  296.  
    head->masking_key[2] = buff[head_len+2];
  297.  
    head->masking_key[3] = buff[head_len+3];
  298.  
     
  299.  
    return head_len +4;
  300.  
    }
  301.  
    return head_len;
  302.  
    }
  303.  
     
  304.  
     
  305.  
    int Websocket_Handler::handlerconn(){
  306.  
     
  307.  
    if(status_ == WEBSOCKET_UNCONNECT){
  308.  
    int len = read(fd_,buff_,BUFFLEN*2);
  309.  
    if (len<=0)
  310.  
    return -1;
  311.  
     
  312.  
    return handshark();
  313.  
    }
  314.  
    printf("Websocket_Handler::handlerconn: begin handlerconn logic.\n");
  315.  
     
  316.  
    recv_request();
  317.  
     
  318.  
    return 0;
  319.  
     
  320.  
     
  321.  
    //int ilenData = 0;
  322.  
    //request_->getReqData(buff_out,buff_len);
  323.  
    snprintf(buff_out,2048,"%s",buff_);
  324.  
     
  325.  
    //send_frame_head();
  326.  
    //request_->print();
  327.  
    //respond client
  328.  
    channel->setRevents(EPOLLOUT|EPOLLET);
  329.  
    channel->getLoop().lock()->updatePoller(channel);
  330.  
     
  331.  
    channel->setWritehandler(bind(&Websocket_Handler::send_respond,this));
  332.  
     
  333.  
    printf("process logic end.\n");
  334.  
    memset(buff_, 0, sizeof(buff_));
  335.  
    return 0;
  336.  
    }
  337.  
     
  338.  
    int Websocket_Handler::handshark(){
  339.  
    char request[1024] = {};
  340.  
    status_ = WEBSOCKET_HANDSHARKED;
  341.  
    fetch_http_info();
  342.  
    parse_str(request);
  343.  
    printf("the respone is %s\n",request);
  344.  
    memset(buff_, 0, sizeof(buff_));
  345.  
    return send_data(request);
  346.  
    }
  347.  
     
  348.  
    char * Websocket_Handler::packData(const char * message,unsigned long * len)
  349.  
    {
  350.  
    char * data=NULL;
  351.  
    unsigned long n;
  352.  
     
  353.  
    n=strlen(message);
  354.  
    if (n < 126)
  355.  
    {
  356.  
    data=(char *)malloc(n+2);
  357.  
    memset(data,0,n+2);
  358.  
    data[0] = 0x81;
  359.  
    data[1] = n;
  360.  
    memcpy(data+2,message,n);
  361.  
    *len=n+2;
  362.  
    }
  363.  
    else if (n < 0xFFFF)
  364.  
    {
  365.  
    data=(char *)malloc(n+4);
  366.  
    memset(data,0,n+4);
  367.  
    data[0] = 0x81;
  368.  
    data[1] = 126;
  369.  
    data[2] = (n>>8 & 0xFF);
  370.  
    data[3] = (n & 0xFF);
  371.  
    memcpy(data+4,message,n);
  372.  
    *len=n+4;
  373.  
    }
  374.  
    else
  375.  
    {
  376.  
     
  377.  
    // 暂不处理超长内容
  378.  
    data=(char *)malloc(n+10); //给data分配内存
  379.  
    if (NULL == data) { //判断data是否为NULL
  380.  
    printf("data is NULL.\n");
  381.  
    return NULL;
  382.  
    }
  383.  
    memset(data,0,n+10); //重置data为0
  384.  
    data[0] = 0x81; //设置第0-7位为1000 0001(FIN为1,Opcode为1)
  385.  
    data[1] = 127; //设置第8-15位为0111 1111
  386.  
    data[2] = (n>>56 & 0xFF); //设置第16-23位为n-128(将n右移8位在与1111 1111做与运算)
  387.  
    data[3] = (n>>48 & 0xFF); //设置第24-31位为n-128(将n右移8位在与1111 1111做与运算)
  388.  
    data[4] = (n>>40 & 0xFF); //设置第32-39位为n-128(将n右移8位在与1111 1111做与运算)
  389.  
    data[5] = (n>>32 & 0xFF); //设置第40-47位为n-128(将n右移8位在与1111 1111做与运算)
  390.  
    data[6] = (n>>24 & 0xFF); //设置第48-55位为n-128(将n右移8位在与1111 1111做与运算)
  391.  
    data[7] = (n>>16 & 0xFF); //设置第56-63位为n-128(将n右移8位在与1111 1111做与运算)
  392.  
    data[8] = (n>>8 & 0xFF); //设置第64-71位为n-128(将n右移8位在与1111 1111做与运算)
  393.  
    data[9] = (n & 0xFF); //设置第72-79位为n的右8(0-7)位
  394.  
    memcpy(data+10,message,n); //将message添加到第10个字节之后
  395.  
    *len=n+10;
  396.  
    }
  397.  
     
  398.  
     
  399.  
    return data;
  400.  
    }
  401.  
     
  402.  
     
  403.  
    int Websocket_Handler::send_respond()
  404.  
    {
  405.  
    printf("recive:%s,len:%d.\n",buff_out,buff_len);
  406.  
    char * respData;
  407.  
    unsigned long respLen = buff_len;
  408.  
    respData=packData(buff_out,&respLen);
  409.  
    printf("packData:%s,len:%d.\n",respData,respLen);
  410.  
    if( !respData || respLen <= 0 )
  411.  
    {
  412.  
    printf("data is empty!\n");
  413.  
    return -1;
  414.  
    }
  415.  
     
  416.  
    //umask(buff_out,buff_len,request_->getMaskKey());
  417.  
    //printf("send:%s.\n",buff_out);
  418.  
     
  419.  
    int len = write(fd_, respData, respLen);
  420.  
    free(respData);
  421.  
    channel->setRevents(EPOLLIN|EPOLLET);
  422.  
    channel->getLoop().lock()->updatePoller(channel);
  423.  
    return len;
  424.  
    }
  425.  
     
  426.  
    void Websocket_Handler::parse_str(char *request){
  427.  
    strcat(request, "HTTP/1.1 101 Switching Protocols\r\n");
  428.  
    strcat(request, "Connection: upgrade\r\n");
  429.  
    strcat(request, "Sec-WebSocket-Accept: ");
  430.  
    std::string server_key = header_map_["Sec-WebSocket-Key"];
  431.  
    server_key += MAGIC_KEY;
  432.  
     
  433.  
    SHA1 sha;
  434.  
    unsigned int message_digest[5];
  435.  
    sha.Reset();
  436.  
    sha << server_key.c_str();
  437.  
     
  438.  
    sha.Result(message_digest);
  439.  
    for (int i = 0; i < 5; i++) {
  440.  
    message_digest[i] = htonl(message_digest[i]);
  441.  
    }
  442.  
    server_key = base64_encode(reinterpret_cast<const unsigned char*>(message_digest),20);
  443.  
    server_key += "\r\n";
  444.  
    strcat(request, server_key.c_str());
  445.  
    strcat(request, "Upgrade: websocket\r\n\r\n");
  446.  
    }
  447.  
     
  448.  
    int Websocket_Handler::fetch_http_info(){
  449.  
    std::istringstream s(buff_);
  450.  
    std::string request;
  451.  
     
  452.  
    std::getline(s, request);
  453.  
    if (request[request.size()-1] == '\r') {
  454.  
    request.erase(request.end()-1);
  455.  
    } else {
  456.  
    return -1;
  457.  
    }
  458.  
     
  459.  
    std::string header;
  460.  
    std::string::size_type end;
  461.  
     
  462.  
    while (std::getline(s, header) && header != "\r") {
  463.  
    if (header[header.size()-1] != '\r') {
  464.  
    continue; //end
  465.  
    } else {
  466.  
    header.erase(header.end()-1); //remove last char
  467.  
    }
  468.  
     
  469.  
    end = header.find(": ",0);
  470.  
    if (end != std::string::npos) {
  471.  
    std::string key = header.substr(0,end);
  472.  
    std::string value = header.substr(end+2);
  473.  
    header_map_[key] = value;
  474.  
    }
  475.  
    }
  476.  
     
  477.  
    return 0;
  478.  
    }
  479.  
     
  480.  
    int Websocket_Handler::send_data(char *buff){
  481.  
    return write(fd_, buff, strlen(buff));
  482.  
    }
  483.  
     
  484.  
    int Websocket_Handler::send_frame_head()
  485.  
    {
  486.  
    char *response_head;
  487.  
    int head_length = 0;
  488.  
    if(buff_len<126)
  489.  
    {
  490.  
    response_head = (char*)malloc(2);
  491.  
    response_head[0] = 0x81;
  492.  
    response_head[1] = buff_len;
  493.  
    head_length = 2;
  494.  
    }
  495.  
    else if (buff_len<0xFFFF)
  496.  
    {
  497.  
    response_head = (char*)malloc(4);
  498.  
    response_head[0] = 0x81;
  499.  
    response_head[1] = 126;
  500.  
    response_head[2] = (buff_len >> 8 & 0xFF);
  501.  
    response_head[3] = (buff_len & 0xFF);
  502.  
    head_length = 4;
  503.  
    }
  504.  
    else
  505.  
    {
  506.  
    //no code
  507.  
    response_head = (char*)malloc(12);
  508.  
    // response_head[0] = 0x81;
  509.  
    // response_head[1] = 127;
  510.  
    // response_head[2] = (head->payload_length >> 8 & 0xFF);
  511.  
    // response_head[3] = (head->payload_length & 0xFF);
  512.  
    head_length = 12;
  513.  
    }
  514.  
     
  515.  
    if(write(fd_,response_head,buff_len)<=0)
  516.  
    {
  517.  
    perror("write head");
  518.  
    return -1;
  519.  
    }
  520.  
     
  521.  
    free(response_head);
  522.  
    return 0;
  523.  
    }
  524.  
     
  525.  
    void Websocket_Handler::umask(char *data,int len,char *mask)
  526.  
    {
  527.  
    int i;
  528.  
    for (i=0;i<len;++i){
  529.  
    *(data+i) ^= *(mask+(i%4));
  530.  
    }
  531.  
    }

我在测试的时候采用的是两台机器,客户端读取音频文件,每次固定2K连续发送数据,最有一帧不足2K场景。

所以在测试的时候会发现服务器端收到的数据包现象如下:

第一次接收一个整包2K

中间接收数据有半包、有满包情况;还有一次读取两帧数据的场景,这时在处理完一帧数据时,再判断是否还粘着的下一帧数据,并校验数据是否时满帧,如果不是,再继续read,直到满帧,解析数据

posted @ 2020-05-15 13:59  亡命之徒ali  阅读(5121)  评论(0编辑  收藏  举报