Connect Websocket with Poco libraries

荒凉一梦 提交于 2020-01-01 06:11:09

问题


I am trying to connect to the Echo Test Websocket using the Poco C++ libraries. In order to do so here is my code which should set up the Websocket:

HTTPClientSession cs("echo.websocket.org");
HTTPRequest request(HTTPRequest::HTTP_GET, "/ws");
HTTPResponse response;

WebSocket* m_psock = new WebSocket(cs, request, response);
m_psock->close(); //close immidiately

However it does not work: I am getting an error message like this:

Poco::Exception: WebSocket Exception: Cannot upgrade to WebSocket connection: Not Found

Can anybody help?


回答1:


The 'Not Found' error is the standard HTTP 404 Not Found returned by the HTTP server. It generally means the resource you are requesting does not exist.

I got your code to work by changing the resource from "/ws" to "/":

HTTPRequest request(HTTPRequest::HTTP_GET, "/");

and adding the following line

request.set("origin", "http://www.websocket.org");

before creating the new WebSocket. I think it's a header pair that many (or all?) WebSocket servers expect.




回答2:


If you want to get a reply from the echo server you must also make sure to use a Http 1.1 request. Poco defaults to Http 1.0.

HTTPRequest request(HTTPRequest::HTTP_GET, "/",HTTPMessage::HTTP_1_1);

This is a complete example,

#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/Net/HTTPClientSession.h"
#include <iostream>

using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::Net::WebSocket;


int main(int args,char **argv)
{
    HTTPClientSession cs("echo.websocket.org",80);    
    HTTPRequest request(HTTPRequest::HTTP_GET, "/?encoding=text",HTTPMessage::HTTP_1_1);
    request.set("origin", "http://www.websocket.org");
    HTTPResponse response;


    try {

        WebSocket* m_psock = new WebSocket(cs, request, response);
        char *testStr="Hello echo websocket!";
        char receiveBuff[256];

        int len=m_psock->sendFrame(testStr,strlen(testStr),WebSocket::FRAME_TEXT);
        std::cout << "Sent bytes " << len << std::endl;
        int flags=0;

        int rlen=m_psock->receiveFrame(receiveBuff,256,flags);
        std::cout << "Received bytes " << rlen << std::endl;
        std::cout << receiveBuff << std::endl;

        m_psock->close();

    } catch (std::exception &e) {
        std::cout << "Exception " << e.what();
    }

}


来源:https://stackoverflow.com/questions/18532388/connect-websocket-with-poco-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!