4

我正在尝试使用Poco C++ 库连接到Echo Test Websocket 。为了做到这一点,这是我应该设置 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

但是它不起作用:我收到如下错误消息:

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

有人可以帮忙吗?

4

2 回答 2

3

“未找到”错误是 HTTP 服务器返回的标准 HTTP 404 Not Found。这通常意味着您请求的资源不存在。

我通过将资源从更改"/ws""/"

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

并添加以下行

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

在创建新的WebSocket. 我认为这是许多(或全部?)WebSocket 服务器所期望的头对。

于 2013-11-14T03:14:37.023 回答
3

如果您想从回显服务器获得回复,您还必须确保使用 Http 1.1 请求。Poco 默认为 Http 1.0。

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

这是一个完整的例子,

#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();
    }

}
于 2014-11-14T14:26:15.187 回答