2013-08-30 128 views
3

我試圖使用Poco C++庫連接到Echo Test Websocket。 爲了這樣做的,是我的代碼應該建立的WebSocket:將Websocket連接到Poco庫

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 

人幫助?

親切的問候

+1

我會問,關於[波蘇論壇](http://pocoproject.org/forum/) –

+0

我這樣做,但沒有幫助:/ – Moonlit

回答

3

的 'Not Found' 錯誤是標準的HTTP 404 NOT FOUND由HTTP服務器返回。它通常意味着你正在請求的資源不存在。

我收到了你的代碼,通過改變從"/ws"資源合作,"/"

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

,並創建新WebSocket之前添加以下行

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

。我認爲這是許多(或全部)WebSocket服務器期望的標頭對。

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

}