Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send websocket PONG response using POCO

I am trying to set up a websocket server using POCO 1.7.5.

The sample from POCO found here works well. Lines 111-122 reads (sligthly prettified):

WebSocket ws(request, response);
char buffer[1024];
int n, flags;

do
{
    n = ws.receiveFrame(buffer, sizeof(buffer), flags);
    ws.sendFrame(buffer, n, flags);
}
while (n > 0 && (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);

However, this approach does not take care of answering ping frames by pong frames. How do I do this properly using POCO? I tried the following, but I dont know if it is correct:

WebSocket ws(request, response);
char buffer[1024];
int n, flags;

do
{
    n = ws.receiveFrame(buffer, sizeof(buffer), flags);
    if ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_PING){
        buffer[0] = WebSocket::FRAME_OP_PING;
        ws.sendFrame(buffer, 1, WebSocket::FRAME_OP_PONG);
    }
    else{
        ws.sendFrame(buffer, n, flags);
    }
}               
while (n > 0 && (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);

Dont know if this is the right way of doing it, and cannot find how to do it online, including the POCO documentation. The websocket RFC 6465 holds loads of info, but I dont want to go there, as I just want to use the websocket as an application programmer here

like image 681
Stefan Karlsson Avatar asked Jan 26 '17 15:01

Stefan Karlsson


1 Answers

From RFC you must send the same buffer with WebSocket::FRAME_OP_PONG flag. Try this:

do
{
    n = ws.receiveFrame(buffer, sizeof(buffer), flags);
    if ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_PING) {
        ws.sendFrame(buffer, n, WebSocket::FRAME_OP_PONG);
    }
    else {
        ws.sendFrame(buffer, n, flags);
    }
}               
while (n > 0 && (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
like image 191
Patricklaf Avatar answered Nov 07 '22 09:11

Patricklaf