1

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 ?

TerryG
  • 309
  • 1
  • 10
nschoe
  • 1,967
  • 1
  • 19
  • 26

1 Answers1

2

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.

n0p
  • 3,399
  • 2
  • 29
  • 50
  • 1
    Yes, that's what actually solved it. I had forgotten to memset the rest of the buffer. Ho an besides, I got the `len` argument wrong too : in case anyone stumbles on the same problem, it is only the length of the data, **not** including the LWS POST and PRE padding. :-) Thanks for the quick answers – nschoe Aug 29 '14 at 14:04
  • I did memeset buffer after writing the data,but still i am getting the same error.Whatever the length i am sending from CPP and same length i am receiving @Java script. – venkat2010 Jun 30 '16 at 09:25