Search code examples
c++websocketwinsockwinsock2

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


I'm trying to make a handshake between my WinSock client and a WebSocket echo server (in my case wss://echo.websocket.org, from https://www.websocket.org/echo.html). As I understand, it connects ok, no errors. Also no errors when I try to send my handshake header, but on receive I get 0.

Some code snippets:

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);
....

And here, recv returns 0, but, if everything would be fine, should return a response header.

So, now I'm stuck, and any suggestion would help a lot...

Also I would be very thankful if someone would recommend any other native/lightweight(header only) c++ lib for an easy work with websockets

Thanks in advance !


Solution

  • recv() returns 0 when the remote peer gracefully closes the connection on their end.

    You are trying to request a WSS (secure WebSocket) resource from an HTTPS (secure HTTP) port. As such, you need to first complete an SSL/TLS handshake with the server before you can then send the WebSocket handshake. You are not doing the SSL/TLS portion, so the server disconnects you immediately.

    Winsock has no concept of SSL/TLS. You need to use Microsoft's SChannel API, or a 3rd party library like OpenSSL, on top of your socket connection.

    You are better off using a 3rd party WebSocket library that handles these details for you.