Chrome从libwebsockets接收时说“无法将文本框架解码为UTF-8”

时间:2014-08-29 13:24:39

标签: javascript c utf-8 websocket libwebsockets

我正在使用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 : %s\n",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方面,Web套接字连接已关闭,Chrome说:"无法将文本框架解码为UTF-8"。

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

1 个答案:

答案 0 :(得分:2)

  

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

你确定吗?

您将返回p;即buf,其大小为LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING,但您只设置了#34;答案"加上\0

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

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