直接从Uwebsockets服务器读取Uint8array

Read uint8array directly from uWebsockets server

本文关键字:读取 Uint8array 服务器 Uwebsockets      更新时间:2023-10-16

我正在尝试使用uwebsockets库读取从Web客户端发送的二进制阵列数据。

我找到了一个有关回购问题的问题,该问题描述了这是针对文本/blob数据的情况,但是我想解析来自Web客户端的uint8array数据:

  • https://gist.github.com/westhorburn/581D8B7A0ED70BC386B8C38883336AD318

  • https://github.com/unetworking/uwebsockets/issues/508

我正在使用非常简单的示例客户端:

int main()
{
    uWS::Hub h;
    h.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) {
        uint8_t messageString [length]; //Create char array with length of message length
        cout << "length: " << length << endl;
        for (int i = 0; i < length; i++) { //Iterate through each character in the message
          messageString[i] = (uint8_t)message[i];   //Add message character to messageString
        }
        cout << "Message: " << &messageString[1] << endl;
        ws->send (message, length, opCode);
    });
    h.listen (3000);
    h.run();
}

在客户端我做:

 {
     ws = new WebSocket(wsUri);
     ws.binaryType = "arraybuffer";
     ws.onopen     = function (evt) { onOpen(evt) };
     ws.onclose    = function (evt) { onClose(evt) };
     ws.onmessage  = function (evt) { onMessage(evt) };
     ws.onerror    = function (evt) { onError(evt) };
 }

并将uint8array向下发送插座。文本/斑点示例不起作用,试图将其读成uint8_t阵列不起作用,我无法确定自己的一生读取如何读取此内容,以便数据可用。请注意,回声回到客户端确实有效 - 我拿回来了。

从客户端阅读数据并响应它们很简单:

h.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t, length, uWS::OpCode opCode) {
    std::string receivedMessage(message, length);
    ws->send("Reponse from server", uWS::OpCode::BINARY);
});