With plain HTTP, the browser asks, the server answers, and that’s the end of it. To learn that a new message had arrived, the browser used to ask every few seconds (polling), which wastes resources and delays messages. The WebSocket standard, RFC 6455, was published in 2011 to solve that.
How it works
- Handshake: the browser sends an HTTP request with
Upgrade: websocket,Connection: Upgradeand aSec-WebSocket-Key. - The server replies with
101 Switching Protocols. - The TCP connection stays open, and both sides exchange text or binary frames whenever they like.
- One side sends a close frame or the connection drops, and the client reconnects.
| Plain HTTP | WebSocket | |
|---|---|---|
| Who starts a message | Always the client | Either side |
| Connection | Request, then response | Persistent |
| URL scheme | https:// |
wss:// |
| Good for | Pages and APIs | Chat, games, live dashboards |
Example: a browser client
const ws = new WebSocket("wss://example.com/chat");
ws.onopen = () => ws.send(JSON.stringify({ type: "join", room: "support" }));
ws.onmessage = (event) => console.log("message:", event.data);
ws.onclose = () => console.log("disconnected, retry shortly");
On the server side, libraries such as ws or Socket.IO are common in Node.js. Note that Socket.IO is its own protocol on top of WebSocket, so its client can’t talk to a plain WebSocket server.
Common problems
- Behind a proxy or CDN: the intermediary must pass the
Upgradeheader through, or the handshake fails. - Drops after idle timeouts: fix with periodic ping/pong messages.
- Mixed content: an HTTPS page can’t open
ws://: see mixed content. - A long-running process: a WebSocket server must stay running and hold connections in memory, unlike traditional PHP, which ends with each request.
On ArabyHost
Clients that connect out to an external WebSocket service (a Discord bot connecting to Discord’s gateway, for example) run on AI/Developer plans as background processes kept alive by cron; see the Discord bot guide. Running a public WebSocket server that accepts visitor connections depends on the app and your account’s resource limits, so talk to us before relying on it. For simple features like notifications, you can start with Server-Sent Events or periodic polling of an API.
FAQ
What's the difference between ws:// and wss://?
ws:// is unencrypted; wss:// is encrypted with TLS, just like HTTPS. Always use wss:// on public sites, because browsers block ws:// from HTTPS pages.
Do I need WebSocket for every real-time feature?
No. If data only flows from server to browser, such as notifications or streaming an AI model's reply word by word, Server-Sent Events are simpler and run over plain HTTP.
Why does my WebSocket connection drop after a few quiet minutes?
Proxies and firewalls close idle connections after a timeout. Send periodic ping/pong heartbeats and build reconnect logic into the client.