我正在尝试在我的 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 返回 0,但是,如果一切正常,应该返回响应 header 。
所以,现在我卡住了,任何建议都会有很大帮助......
此外,如果有人推荐任何其他 native /轻量级(仅 header )c++ 库以便轻松使用 websockets,我将非常感激
提前致谢!
最佳答案
recv()
当远程对端优雅地关闭他们端的连接时返回 0。
您正在尝试从 HTTPS(安全 HTTP)端口请求 WSS(安全 WebSocket)资源。因此,您需要先完成与服务器的 SSL/TLS 握手,然后才能发送 WebSocket 握手。您没有执行 SSL/TLS 部分,因此服务器会立即断开您的连接。
Winsock 没有 SSL/TLS 的概念。您需要在套接字连接之上使用 Microsoft 的 SChannel API 或 OpenSSL 等第 3 方库。
您最好使用第 3 方 WebSocket 库来为您处理这些细节。
关于c++ - 在 Winsock ws 客户端和 Websocket 服务器之间建立握手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54056936/