@cch137/ws v1.0.23
Introduction
This module extends the functionality of the ws
library, adding support for emitting and handling events, as well as creating and managing WebSocket rooms.
Classes and Prototypes
WS
The WS
prototype is the WebSocket
instance returned by ws.Server
. This prototype has been extended to support emitting and handling events.
Properties
joinedRooms: *Set*
: a set of rooms that the socket has joined.handlers = {}
: an object that maps event names to sets of event handlers.
Methods
on(event: *string*, handler: *Function*)
: adds an event handler for a specific event. If the event name is one of the reserved events (‘close’, ‘error’, ‘message’, ‘open’, ‘ping’, ‘pong’, ‘unexpected-response’, ‘upgrade’), the originalon
method will be used. Otherwise, the event handler will be added to thehandlers
object.emit(event: *string*, data: *any*, callback: *Function*)
: sends an event to the socket. Thecallback
function is called once the message has been sent, or immediately if the socket is not open. Thecallback
function takes an optionalerr
parameter.__on
and__emit
: the originalon
andemit
methods of the WebSocket instance, which are called when handling reserved events or if an error occurs.
WS.Server
The WS.Server
class extends the ws.Server
class, adding support for creating and managing WebSocket rooms.
Properties
rooms = {}
: an object that contains all the rooms created by the server, with room names as keys andWSRoom
objects as values.
Methods
joinRoom(socket: *WS*, roomName: *string*, key: *string*)
: joins a socket to a room. A room with the given name is created if it doesn’t exist.key
is an optional string that is used to authenticate the socket joining the room.leaveRoom(socket: *WS*, roomName: *string*)
: removes a socket from a room. If the room has no sockets after removing the socket, the room is deleted.broadcastRoom(roomName: *WS*, data: *any*)
: broadcasts a message to all sockets in a room.
WSRoom
The WSRoom
class represents a WebSocket room.
Properties
name: *string*
: the name of the room.key: *string*
: an optional string used to authenticate sockets joining the room.sockets: *WS*
: a set of sockets that have joined the room.
Methods
addSocket(socket: *WS*, key: *string*)
: adds a socket to the room. The given key must match the room’s key, otherwise an error is thrown.removeSocket(socket: *WS*)
: removes a socket from the room.broadcast(event: *string*, data: *any*)
: broadcasts an event to all sockets in the room.
For developer of this module
Commands
npm uninstall @cch137/ws
npm i @cch137/ws
npm init --scope=cch137
git pull
npm publish --access=public
git add .
git commit -am "updated"
git push
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago