ENES

WebSocket

A connection between browser and server that stays open, so both can talk anytime.

On the left, HTTP as separate request and response arrows; on the right, a browser and a server joined by one open pipe with messages flowing both ways

Plain HTTP works like a letter exchange: the browser asks, the server answers, and the conversation is over. The server cannot speak first. A WebSocket is a connection that stays open after it is created, so either side can send a message at any moment, in both directions, without asking again.

It starts as an ordinary HTTP request with a special header that says, in effect, 'let us switch to WebSocket' (the upgrade handshake). If the server agrees, the same TCP connection is kept and from then on carries small messages, called frames, instead of full requests and responses. In the browser it is a few lines of code: new WebSocket("wss://chat.example.com"), then a function that runs every time a message arrives. The wss:// prefix means it is encrypted, like HTTPS.

It is what makes real-time web apps feel instant: chat apps, live sports scores, shared documents where you see other people typing, trading screens, multiplayer browser games. The old alternative was polling, asking the server 'anything new?' every few seconds, which is slower and wastes requests when the answer is no. The cost is that the server has to keep one open connection per user, which takes memory and care when scaling, and connections drop on bad networks, so apps must reconnect.

Keep in mind

Go deeper

Related terms

More in Networks