Search code examples
javascriptcutf-8websocketlibwebsockets

Chrome says "Could not decode a text frame as UTF-8" when receiving from libwebsockets


I'm using libwebsockets C library. I'm trying to do a simple echo server, as a test. I'm testing with Firefox and Chrome under linux.

The pieces of code are simple :

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;
    }

}

I do receive the 'This is a hello' from the browser, but when I send the answer, it does write 'Wrote 534 bytes' but on hte Javascript side, the web socket connection is closed, and Chrome says : "Could not decode a text frame as UTF-8".

I'm confused, in the string "Answer", there are only < 128 characters, so they should be UTF-8, right ?


Solution

  • I'm confused, in the string "Answer", there are only < 128 characters, so they should be UTF-8, right ?

    Are you sure ?

    You are returning p; i.e. buf, which size is LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING but you are only setting the 6 chars of "Answer" plus the \0.

    My guess is the rest of buf contains random bytes, most likely no UTF-8 characters.

    You should memset your buffer with 0 before filling it and use strncpy.