1 /* 2 Vertion: 0.2.1 3 date: 2015.8.11 4 content: gcc 编译通过 5 */ 6 7 //websocket 传输数据帧打包 client端 8 //参数:src 为输入字符串 9 // len为输入字串src长度 10 // mask为4个字节掩码值 11 // des 为输出掩码后字节数组。 12 // sum 为输出des实际长度 (len+6: len<=125 13 // len+8: 125<len<=65535 14 // len+10: len>65535 15 // 0: 组帧失败) 16 void maskpak(unsigned char src[], 17 unsigned int len, 18 unsigned char mask[], 19 unsigned char des[], 20 unsigned int *sum) 21 { 22 unsigned char FIN =0X80; 23 unsigned char RSV1 =0X00; 24 unsigned char RSV2 =0X00; 25 unsigned char RSV3 =0X00; 26 unsigned char OPCODE =0X01; //文本帧 27 unsigned char MASK =0X80; //掩码标识 28 unsigned char PLEN =0X00; 29 30 int index=0; 31 int i; 32 33 des[index++]= FIN +RSV1 +RSV2 +RSV3 +OPCODE; 34 35 if(len<=125) 36 { 37 PLEN =len; 38 }else if(len<=0XFFFF) 39 { 40 PLEN =126; 41 }else 42 { 43 PLEN =127; 44 } 45 des[index++]= MASK +PLEN; 46 47 //网络字节序标准为: 大端方式(即高字节在前低字节在后) 48 if(PLEN<=125) 49 { 50 *sum= len+6; 51 } 52 else if(126==PLEN) 53 { 54 unsigned short temp; 55 temp =len; 56 des[index++] =(unsigned char)(temp>>8); 57 des[index++] =(unsigned char)temp; 58 *sum= len+8; 59 }else if(127==PLEN) 60 { 61 unsigned int temp; 62 temp =len; 63 des[index++] =(unsigned char)(temp>>24); 64 des[index++] =(unsigned char)(temp>>16); 65 des[index++] =(unsigned char)(temp>>8); 66 des[index++] =(unsigned char)temp; 67 *sum=len+10; 68 }else 69 { 70 *sum= 0; 71 return; 72 } 73 74 for(i=0;i<4;i++) 75 { 76 des[index++] =mask[i]; 77 } 78 79 for(i=0;i<len;i++) 80 { 81 des[index++] =src[i]^mask[i%4]; 82 } 83 } 84 85 // 测试代码 86 int main(int argc,char *argv) 87 { 88 unsigned char src[200]; 89 unsigned char mask[4]= {0X00,0X00,0X00,0X00}; 90 unsigned char des[200+8]; 91 unsigned int len = 200; 92 unsigned int sum; 93 94 int i; 95 96 for (i=0;i<200;i++) 97 { 98 src[i] = i; 99 } 100 maskpak(src,len,mask,des,&sum); 101 102 printf("SUM=%d \r\n",sum); 103 for(i=0;i<sum;i++) 104 { 105 printf("%.2X ",(unsigned char)(des[i])); 106 } 107 108 return 0; 109 }