achieve_rooms
v2.0.0
Published
Simple in-memory rooms and broadcasting for WebSocket applications using ws.
Maintainers
Readme
achieve_rooms
achieve_rooms provides simple, in-memory rooms and broadcasting for WebSocket applications using ws. It was developed and tested with ws; compatibility with other WebSocket implementations has not been tested.
The application creates and owns the HTTP server, WebSocket server, and WebSocket connections. achieve_rooms only groups the supplied connections and broadcasts messages among them.
Install
npm install achieve achieve_rooms wsAchieve and ws quick start
import achieve from "achieve";
import { WebSocketServer } from "ws";
import rooms from "achieve_rooms";
const server = achieve.listen(8989);
const websocketServer = new WebSocketServer({server});
websocketServer.on("connection", (ws,request) => {
rooms.joinRoom(ws,request.url);
ws.on("message", (data,isBinary) => {
rooms.broadcast(ws,data,isBinary);
});
ws.on("close", () => {
rooms.remove(ws);
});
});Connect without a room query parameter to join the default lobby:
const ws = new WebSocket("ws://localhost:8989/");Supply a room name to join a named room:
const ws = new WebSocket("ws://localhost:8989/?room=documents");The selected room name is stored directly on the supplied connection as ws.room. A message therefore does not need to identify its room again. Rooms are created when first used and deleted after their last connection is removed.
rooms.broadcast(ws,data,isBinary) sends to the other connections in ws.room; it does not echo the message to the sender. Passing the isBinary value supplied by the ws message event preserves text and binary message types.
API
rooms.joinRoom(ws,url)
Adds ws to the room selected by the first nonempty room query parameter in url, or to lobby when no room is supplied. Room membership is stored as ws.room.
rooms.broadcast(ws,data[,isBinary])
Sends data to every other live connection in the sender's room. The optional isBinary flag is forwarded using the ws send options.
rooms.remove(ws)
Removes a connection from its room. Removing the final connection deletes the room.
rooms.theRooms
The process-local room registry. It is a Map whose room names map to Sets of WebSocket connections.
Scope
Room state exists only in the current Node.js process. It is not persistent and is not shared among cluster workers or multiple servers. Applications that need distributed or durable room state require an external coordination or storage system.
The application remains responsible for authentication, authorization, connection lifecycle, server configuration, and choosing acceptable room names.
License
MIT
