Network - WebSocket Protocol

About

WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection between:

with lower overheads, facilitating real-time data transfer from and to the server.

Implementation

WebSocket is running over a single TCP connection where:

  • The server can send content to the client without being first requested by the client.
  • The communications are done over TCP port number 80 (or 443 in the case of TLS-encrypted connections)

Websocket is located at layer 7 in the OSI model (and, as such, depend on TCP at layer 4)

RFC 6455 states that WebSocket is designed to:

Similar two-way browser-server communications have been achieved in non-standardized ways using stopgap technologies such as Comet.

Standardization

The WebSocket:

  • protocol was standardized by the IETF as RFC 6455 in 2011,
  • API in Web IDL is being standardized by the W3C.

Usage

Push real-time updates such as:

  • notifications,
  • vote counts,
  • new answers
  • comments

Library

Native Javascript

WebAPI WebSocket

var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

Websocket.io

Example

Documentation / Reference


Powered by ComboStrap