Chrome 在从 libwebsocket 接收时说"Could not decode a text frame as UTF-8"



我使用的是libwebsockets C库。我正在尝试做一个简单的echo服务器,作为一个测试。我正在linux下测试Firefox和Chrome。

代码很简单:

Javascript

var ws = new WebSocket ("ws://127.0.0.1:9999", "hephaestus");
ws.onopen = function() {
    console.log ('Connection opened.');
    setTimeout (function() {
        ws.send ('This is a hello.n');
    }, 2000);
};
ws.onerror = function() {
    console.log ('Error in connection');
};
ws.onclose = function() {
    console.log ('Connection closed');
};
ws.onmessage = function (msg) {
    console.log ('Message received : ' + msg.data);
};

C

ephaestus_callback(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
    int n, m;
    unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];
    unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
    unsigned char *ret = "Answer";
    switch (reason)
    {
        case LWS_CALLBACK_RECEIVE:
        printf("Received : %sn",in);
        strcpy (p, ret);
        n = libwebsocket_write (wsi, buf, LWS_SEND_BUFFER_POST_PADDING + 512 + LWS_SEND_BUFFER_PRE_PADDING, LWS_WRITE_TEXT);
        printf ("Wrote %d bytes.n", n);
        break;
    }
}

我确实收到了来自浏览器的"这是你好",但当我发送答案时,它确实写着"写入534字节",但在Javascript方面,网络套接字连接关闭,Chrome说:"无法将文本帧解码为UTF-8"。

我很困惑,在字符串"Answer"中,只有<128个字符,所以它们应该是UTF-8,对吧?

我很困惑,在字符串"Answer"中,只有<128个字符,所以它们应该是UTF-8,对吧?

你确定吗?

您正在返回p;即buf,其大小为LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING,但您仅设置"Answer"的6个字符加上

我的猜测是buf的其余部分包含随机字节,很可能没有UTF-8字符。

在填充缓冲区并使用strncpy之前,您应该使用0memset缓冲区。

相关内容

  • 没有找到相关文章

最新更新