- Realtime communication.
- Bidirectional communication mean.
- This type of connection is often referred to as full-duplex connection.
- Provide communication channel over a single Transmission Control Protocol (TCP) connection.
In the majority of cases, your client should not use WebSockets to stay up to date with your backend, instead you can use:
- Short polling: Poll intermittently with queries.
- Re-execute queries on demand: when a user performs a relevant action (e.g. clicking on a refresh button) refetch data.
- Large objects, small, incremental changes:
- Short polling a large object is expensive, especially here since most of the object's fields have not changed.
- Instead:
- Fetch the object's initial state with a query.
- Server proactively push updates to individual fields as they occur.
- Low-latency, real-time updates:
- Clients in a chat app want to receive new messages ASAP.
-
Client asks server to form a WebSocket connection.
GET ws://example.com HTTP/1.1 Connection: Upgrade Upgrade: websocket
-
Server says let's do it (handshake completed successfully and server responses):
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade
Done, now:
- From this point onward we have an open TCP/IP connection open.
- Each party can send message to the other party instantly.
- The connection closes when one party drops off.
- We need a backend:
apps/websocket-backend
: - We need a client:
apps/websocket-client
.
Important
ws
library is good and all but you need to reinvent the wheel many times. Like broadcasting a message and things like that.
ws
is a low-level library. But for a real world app most of the times we need something a bit more mature.
- Alternatives to socket.io:
- Might like to learn about some of the challenges of building a realtime app.
- To see how you acn use
socket.io
see ourchat-backend
andchat-frontend
app.