About
WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection between:
- a web client (such as a browser)
- and a web server.
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:
- work over HTTP ports 80 and 443
- support HTTP proxies and intermediaries
Similar two-way browser-server communications have been achieved in non-standardized ways using stopgap technologies such as Comet.
Standardization
The WebSocket:
- 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
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
- raw_websocket.js - puppeteer - shows how to use raw web sockets to send messages to the page using the DevTools protocol.