Implementing Real‑Time Multi‑Device Communication with WebSocket in ThinkJS
This article explains how to use ThinkJS, a Koa‑based Node.js framework, together with WebSocket and Socket.io to build a multi‑device real‑time chat system, covering protocol basics, server and client configuration, a simple chat demo, and scaling across multiple nodes using Redis.
The guide introduces WebSocket as an HTML5 protocol that enables true server‑push communication, contrasting it with polling and long‑polling approaches, and explains why WebSocket is needed for real‑time messaging.
It then shows how to configure ThinkJS (a Koa 2 based enterprise Node.js framework) for WebSocket support by enabling stickyCluster in src/config/config.js and adding the WebSocket plugin in src/config/extend.js and src/config/adapter.js .
Server‑side code is illustrated with a controller that extends think.Controller , sets up this.io and this.socket , and implements openAction , closeAction , messageAction and roomAction to handle connection lifecycle and message broadcasting.
On the client, a simple inclusion of <script src="https://lib.baomitu.com/socket.io/2.0.1/socket.io.js"></script> creates a socket instance, listens for open , message and room events, and emits chat messages.
A minimal chat UI is built with Vue templates that render entry/exit tips and chat messages, using a global variable global.$socketChat to store socket handles for user identification.
To address multi‑node deployment, the article introduces a Redis‑backed registry ( -socket-chat ) that records which server IP holds each WebSocket connection, and a crossSync method that publishes actions to other nodes via HTTP requests.
It also covers two Redis‑based scaling solutions: a custom pub/sub implementation using Redis hashes and the official socket.io-redis adapter, which abstracts the pub/sub logic.
Finally, the guide mentions the socket.io-emitter library for sending events to a Socket.io cluster from non‑Socket.io processes (e.g., plain HTTP services) and provides a link to the full source code on GitHub.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.