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:
HTTPClie
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();
}
}
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.