Skip to main content

WebSocket

WebSocket is one of the ways a browser and a server exchange data. Unlike HTTP, it is a persistent, bidirectional connection, so there is no reconnecting or resending of headers and other redundant overhead, and it responds more immediately. The formal IETF standard is RFC 6455.

WebSocket has two parts: a programming interface in the browser, and a transport protocol on the server side.

Protocol

You can choose the ws or wss scheme. ws is equivalent to plain HTTP and wss to HTTPS, but the server must support the secure variant.

Because the connection is persistent, the URI does not change during a session, so you connect to exactly one URI at a time. To talk to a different URI, open a new WebSocket connection.

Browser API

Sending data is a call to send(). To receive data, handle the onmessage event. Calling close() ends the connection.

Handshake

The connection starts with a handshake: the browser sends an HTTP-compatible request carrying the WebSocket-defined headers. The server processes them and returns the result in its response headers. Once the browser validates the returned headers, both sides establish the data link and exchange messages until close() is called.