websocket 发送数据大于0xFFFF(65535)的处理

网上很多关于websocket发送数据大于大于0xFFFF(65535)的处理都是一句话“暂不处理”!!!!!所以特写此文。

int WSSession::safeSendFrame(uint8_t *buffer, size_t bufferSize, enum wsFrameType frameType) 
{
// 发数据到浏览器需要封装一个websocket的头,但wsMakeFrame()函数存在内存拷贝,会消耗性能,
// 所以这里分两步发:1、发websocket头,2、发实际数据。


// 构造websocket头
uint8_t wsMakeFrameHead[20] = {0};
size_t FrameHeadLen = 0;
assert(frameType < 0x10);
if (bufferSize > 0)
assert(buffer);


wsMakeFrameHead[0] = 0x80 | frameType;


if (bufferSize <= 125) {
wsMakeFrameHead[1] = bufferSize;
FrameHeadLen = 2;
} else if (bufferSize <= 0xFFFF) {
wsMakeFrameHead[1] = 126;
uint16_t payloadLength16b = htons(bufferSize);
memcpy(&wsMakeFrameHead[2], &payloadLength16b, 2);
FrameHeadLen = 4;
} else {
//        assert(dataLength <= 0xFFFF);


//implementation for 64bit systems
/*wsMakeFrameHead[1] = 127;
uint64_t lenHigh32b = htonl((bufferSize>>32)& 0xFFFFFFFF);
uint64_t lenLow32b = ((uint64_t)htonl(bufferSize&0xFFFFFFFF)) << 32;


uint64_t payloadLength64b = lenHigh32b | lenLow32b;
memcpy(&wsMakeFrameHead[2], &payloadLength64b, 8);
FrameHeadLen = 10;*/


wsMakeFrameHead[1] = 127;
wsMakeFrameHead[2] = 0;
wsMakeFrameHead[3] = 0;
wsMakeFrameHead[4] = 0;
wsMakeFrameHead[5] = 0;
wsMakeFrameHead[6] = (byte)(bufferSize >>24);
wsMakeFrameHead[7] = (byte)(bufferSize >>16);
wsMakeFrameHead[8] = (byte)(bufferSize >>8);
wsMakeFrameHead[9] = (byte)(bufferSize & 0xFF);
FrameHeadLen = 10;
}


// 发websocket头
int nRetH = safeSend(wsMakeFrameHead, FrameHeadLen);


// 发实际数据
int nRetD = safeSend(buffer, bufferSize);


if (nRetH != EXIT_SUCCESS || nRetD != EXIT_SUCCESS)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}

你可能感兴趣的:(C++技术,web)