Search code examples
httptcpwebsockethandshake

Why do we use the \n\r in the websocket handshake response?


Why do we use the \r\n in the HTTP headers for JS WebSocket handshake response and two times \r\n\r\n at the end, but not in handshake request? Is it possible to do the handshake response without adding the \r\n?

Are the \r\n also used in TCP sockets or is it only used for JS WebSocket?

For example:

"Upgrade: something\r\n".
"Connection: something\r\n".
// ...
"Sec-WebSocket-Accept: something\r\n\r\n";

Solution

  • Why do we use the \n\r in HTTP headers for JS WebSocket handshake response ...

    The initial Websocket handshake is HTTP. So the message format used is defined in the HTTP specification. HTTP itself has this idea from earlier standards like RFC 821 (format of mail) which again got this from older stuff - let's just say it evolved that way similar to how languages evolved. One might have done this differently but now it is like this.

    The important part is that all use it the same way and understand it the same way, which includes understanding that it is neither \n\r as you said, not \n as commonly used, but \r\n.

    Are the \n\r is also used in TCP socket or no it is only used for JS WebSocket?

    TCP is an octet stream only where the different transferred bytes have no specific meaning at the level of TCP. Application layer protocols like HTTP or WebSockets add a meaning to the bytes and thus define a structure of the transferred data. Ultimately WebSockets use TCP sockets for the transport of the messages, i.e. WebSockets essentially define structured messages and how they get serialized as bytes in order to be transferred within the data stream TCP provides.