如何使用POCO

时间:2017-01-26 15:59:16

标签: c++ websocket poco-libraries

我正在尝试使用POCO 1.7.5设置websocket服务器。

来自POCO的样本here效果很好。第111-122行读取(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);

但是,这种方法不需要通过乒乓帧来回答ping帧。如何使用POCO正确完成此操作?我试过以下,但我不知道它是否正确:

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

不知道这是否是正确的做法,并且无法在线找到,包括POCO文档。 websocket RFC 6465包含大量信息,但我不想去那里,因为我只想在这里使用websocket作为应用程序员

2 个答案:

答案 0 :(得分:6)

从RFC中,您必须使用WebSocket :: FRAME_OP_PONG标志发送相同的缓冲区。 试试这个:

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

答案 1 :(得分:-1)

do
{
    nbytes = ws->receiveFrame(buffer, sizeof(buffer), flags);
    if ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_PING) {
        std::cout << "PING received\n";
        if (nbytes == 0) nbytes = 1; // Poco destroys active session if we send zero length string
        ws->sendFrame(buffer, nbytes, WebSocket::FRAME_FLAG_FIN | WebSocket::FRAME_OP_PONG);
        std::cout << " PONG sent\n";
        continue;
    }
    if ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_PONG) {
        std::cout << "PONG received\n";
        continue;
    }
    std::cout << nbytes << " bytes received from server:\n";

} while (nbytes > 0 && (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);