在 Winsock ws 客户端和 Websocket 服务器之间建立握手

Establish a handshake between a Winsock ws client and a Websocket server

我正在尝试在我的 WinSock 客户端和 WebSocket 回显服务器之间进行握手(在我的例子中是 wss://echo.websocket.org,来自 https://www.websocket.org/echo.html)。据我了解,它连接正常,没有错误。当我尝试发送我的握手 header 时也没有错误,但在接收时我得到 0.

一些代码片段:

string ipAddress = "174.129.224.73";//echo.websocket ip address
int port = 443;                     // Listening port # on the server

                                        // Initialize WinSock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);

SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);

sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);

// Connect to server
int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));

string header = "GET wss://echo.websocket.org/ HTTP/1.1\r\n"
    "Host: echo.websocket.org\r\n"
    "Upgrade: websocket\r\n"
    "Connection: Upgrade\r\n"
    "Sec-WebSocket-Key: BJZcwnjVSapHLie3s8n0yA==\r\n"
    "Origin: http://localhost\r\n"
    "Sec-WebSocket-Protocol: chat, superchat\r\n"
    "Sec-WebSocket-Version: 13\r\n\r\n";

int sendResult = send(sock, header.c_str(), header.length() + 1, 0);

// Do-while loop to send and receive data
char buf[4096];


int bytesReceived = recv(sock, buf, 4096, 0);
....

在这里,recv returns 0,但是,如果一切正常,应该 return 响应 header。

所以,现在我被困住了,任何建议都会有很大帮助...

此外,如果有人推荐任何其他 native/lightweight(仅限 header)c++ 库以便轻松使用 websockets,我将不胜感激

提前致谢!

recv() returns 0 当远程对等端正常关闭连接时。

您正在尝试从 HTTPS(安全 HTTP)端口请求 WSS(安全 WebSocket)资源。因此,您需要先与服务器完成 SSL/TLS 握手,然后才能发送 WebSocket 握手。您没有执行 SSL/TLS 部分,因此服务器会立即断开您的连接。

Winsock 没有SSL/TLS 的概念。您需要在套接字连接之上使用 Microsoft 的 SChannel API,或像 OpenSSL 这样的第三方库。

您最好使用为您处理这些细节的第 3 方 WebSocket 库。