How do I connect to a websocket manually, with netcat/socat/telnet?

user48678 picture user48678 · Oct 22, 2014 · Viewed 29.2k times · Source

I am trying to connect to the reference websocket echo server "manually", in order to learn how the protocol works (I am using socat for that). However, the server invariably closes the connection without providing an answer. Any idea why?

Here is what I do:

socat - TCP:echo.websocket.org:80

Then, I paste the following text in the terminal:

GET /?encoding=text HTTP/1.1
Origin: http://www.websocket.org
Connection: Upgrade
Host: echo.websocket.org
Sec-WebSocket-Key: P7Kp2hTLNRPFMGLxPV47eQ==
Upgrade: websocket
Sec-WebSocket-Version: 13

I sniffed the parameters of the connection with the developer tools, in firefox, on the same machine, where this works flawlessly: therefore, I would assume they are correct. However after that, the server closes the connection immediately, without providing an answer. Why? How can I implement the protocol "manually"?

I would like type test in my terminal and get the server to reply with what I typed (It works in a web browser).

Answer

Michael Petch picture Michael Petch · Oct 30, 2014

I think you want to modify the socket stream to translate \n (line feed) to CRLF (Carriage return & line feed). Doing info socat produces detailed information which includes this modifier:

crnl   Converts the default line termination character NL ('\n',  0x0a)
       to/from CRNL ("\r\n", 0x0d0a) when writing/reading on this chan-
       nel (example).  Note: socat simply strips all CR characters.

So I think you should be able to do this:

socat - TCP:echo.websocket.org:80,crnl