เชื่อมต่อ Websocket กับไลบรารี Poco

ฉันกำลังพยายามเชื่อมต่อกับ Echo Test Websocket โดยใช้ Poco ไลบรารี C++ ในการทำเช่นนั้น นี่คือโค้ดของฉันที่ควรตั้งค่า 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

ใครสามารถช่วยได้บ้าง?


person Moonlit    schedule 30.08.2013    source แหล่งที่มา
comment
ฉันจะถามสิ่งนั้นในฟอรัม Poco   -  person Basile Starynkevitch    schedule 30.08.2013
comment
ฉันทำอย่างนั้น แต่ก็ช่วยไม่ได้ :/   -  person Moonlit    schedule 02.09.2013


คำตอบ (2)


ข้อผิดพลาด 'ไม่พบ' คือ HTTP 404 ไม่พบมาตรฐานที่ส่งคืนโดยเซิร์ฟเวอร์ HTTP โดยทั่วไปหมายความว่าทรัพยากรที่คุณร้องขอไม่มีอยู่

ฉันได้รับรหัสของคุณให้ใช้งานได้โดยเปลี่ยนทรัพยากรจาก "/ws" เป็น "/":

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

และเพิ่มบรรทัดต่อไปนี้

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

ก่อนที่จะสร้าง WebSocket ใหม่ ฉันคิดว่ามันเป็นคู่ส่วนหัวที่เซิร์ฟเวอร์ WebSocket จำนวนมาก (หรือทั้งหมด) คาดหวัง

person Kevin H. Patterson    schedule 14.11.2013

หากคุณต้องการรับการตอบกลับจากเซิร์ฟเวอร์ echo คุณต้องแน่ใจว่าใช้คำขอ 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();
    }

}
person Olof    schedule 14.11.2014