如何在65536字节上编码二进制数据到C 上的WebSocket帧
How to encode binary data over 65536 bytes to websocket frame on c++
我的服务器在STD :: String Buffer(ANSI(中保存JPEG-File。我需要应要求将其发送到网络客户。我接下来尝试了:
std::string ws_encode(std::string frame) {
string result;
result.resize(2);
result[0]= 130;
if (frame.size() <= 125) {result[1]=frame.size();}
else if (frame.size() >= 126 && frame.size() <= 65535) {
result.resize(4);
result[1] = 126;
result[2] = ( frame.size() >> 8 ) && 255;
result[3] = ( frame.size() ) && 255;
}
else {
result.resize(10);
result[1] = 127;
result[2] = ( frame.size() >> 56 ) && 255;
result[3] = ( frame.size() >> 48 ) && 255;
result[4] = ( frame.size() >> 40 ) && 255;
result[5] = ( frame.size() >> 32 ) && 255;
result[6] = ( frame.size() >> 24 ) && 255;
result[7] = ( frame.size() >> 16 ) && 255;
result[8] = ( frame.size() >> 8 ) && 255;
result[9] = ( frame.size() ) && 255;
}
return result+frame;
}
,然后:
string encoded_frame = ws_encode(Agents["65535"].Screen); // it's a map <string id, struct Agent>, Agent has string Screen buffer for screenshots
send(client_socket, &encoded_frame[0], encoded_frame.size(), 0);
但是,浏览器在没有控制台中没有任何解释的情况下关闭了连接。也许长度计算是错误的,或者并非所有数据都发送了...我不知道 - 在发送看起来正确之前,用编码数据编写test.txt。
有人可以帮助我完成此任务吗?
设置有效载荷长度值的字节时,当您应该使用BITWISE AND
(&
(运算符时,您将使用LOGICAL AND
(&&
(运算符。
尝试更多这样的东西:
std::string ws_encode(char opcode, const std::string &data)
{
string result;
std::string::size_type size = data.size();
if (size <= 125)
{
result.resize(2+size);
result[0] = 0x80 | opcode;
result[1] = (char) size;
}
else if (size <= 65535)
{
result.resize(4+size);
result[0] = 0x80 | opcode;
result[1] = 126;
result[2] = (size >> 8) & 0xFF;
result[3] = (size ) & 0xFF;
}
else
{
result.resize(10+size);
result[0] = 0x80 | opcode;
result[1] = 127;
result[2] = (size >> 56) & 0xFF;
result[3] = (size >> 48) & 0xFF;
result[4] = (size >> 40) & 0xFF;
result[5] = (size >> 32) & 0xFF;
result[6] = (size >> 24) & 0xFF;
result[7] = (size >> 16) & 0xFF;
result[8] = (size >> 8) & 0xFF;
result[9] = (size ) & 0xFF;
}
if (size > 0)
{
memcpy(&result[result.size()-size], data.c_str(), size);
// or:
// std::copy(data.begin(), data.end(), result.begin()+(result.size()-size));
}
return result;
}
std::string encoded_frame = ws_encode(0x02, Agents["65535"].Screen);
send(client_socket, encoded_frame.c_str(), encoded_frame.size(), 0);
相关文章:
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 如何使用数据对象上的常量指针初始化类
- 将字符串与文件上的数据进行比较
- 编译器上的策略数据结构不起作用
- 在PROGMEM中添加更多数据会中断Arduino Mega 2560上的SPI传输
- 在 QAbstractTableModel 上的 setModel 之后插入数据
- 使用 epoll 边缘触发器的套接字上的数据过多
- Windows 上的 Clang/LLVM 7 和 8 多次初始化内联静态数据成员(使用 link.exe 和 lld-
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- 如何在派生类上强制实现特定数据类型的构造函数?
- 是否可以检查存储在堆栈上的单词是否是回文,而C++中没有任何附加数据结构
- 家庭作业帮助 - 检查表单按钮上的数据
- 如何等待 COM 端口上的数据
- 剪贴板数据上使用的全局大小函数会导致错误
- 如何使用CERES :: Cupicinterpolator与不在均匀网格上的数据
- 在服务器关闭的TCP连接上发送数据时的行为不一致
- 使用initializer_list上的数据
- 如何在65536字节上编码二进制数据到C 上的WebSocket帧
- 当并行线程访问同一数据结构的其他成员时,正确的方法可以在Visual Studio上的OpenMP上并行循环
- 关于非纯旧数据上的memset的编译时警告