WebSockets work over HTTP (kind of). They are designed to have a consistent connection between client and a server. Most commonly used for chats, sport updates or trading apps. It is an alternative to HTTP Polling for two-way communication. A connection between client and a server is established upon successful handshake.

Security

WebSockets, by default, only accept Port 80 and Port 443 for connections

Handshake

Handshake is initiated by a client by sending a GET request to a server that a client wants to initialise a bi-directional connection. A handshake from a client looks like this

GET /chat HTTP/1.1  
Host: server.example.com  
Upgrade: websocket  
Connection: Upgrade  
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==  
Origin: http://example.com  
Sec-WebSocket-Protocol: chat, superchat  
Sec-WebSocket-Version: 13  

A client has to include the following headers

  • Host: it is required so that server and client can agree on which host is in use
  • Upgrade : It should always provide the protocol to which you want to update your connection. In this context, it will be websockets
  • Connection: it needs to be provided and set to Upgrade to tell a server that you want to upgrade an established connection with a server
  • Origin: If your client is a web browser, this is required to protect against unauthorised cross-origin access to websocket server
  • Sec-WebSocket-Key: It is important for provide it as it ensures that the handshake is unique. Without this, connection might not be possible to be established.

Optional headers

  • Sec-WebSocket-Protocolheader is not mandatory but can be used to indicate what subprotocols are acceptable to the client. Server selects one or none in a handshake to indicate it has selected that protocol.
How it works
  1. Client sends a randomly generated string . For exampledGhlIHNhbXBsZSBub25jZQ.
  2. Sever takes the header and appends a GUID. For example “dGhlIHNhbXBsZSBub25jZQ==+258EAFA5-E914-47DA-95CA-C5AB0DC85B11`
  3. That value then is hashed using SHA-1 hashing algorithm. Example b37a4f2cc0624f1690f64606cf385945b2bec4ea
  4. Then it is converted to Base64. Example s3pPLMBiTxaQ9kYGzzhZRbK+xOo=.
  5. Server then adds it to

The handshake from the server looks as follows:

HTTP/1.1 101 Switching Protocols  
Upgrade: websocket  
Connection: Upgrade  
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=  
Sec-WebSocket-Protocol: chat  

A handshake from a server, when successful, returns 101 Switching Protocols status code, information about to which connection type that connection has been changed, a generated nonce and the protocol. If that nonce isn’t included or status code isn’t 101, that connection will not be established.