Skip to content

Repository files navigation

@dimensionalpocket/websocket-server

build

Wrapper on µWebSockets.js with opinionated features.

Features

  • Exposes a plain root endpoint with a JSON status page
  • Exposes the webserver on /server
  • Upgrades connections with UUIDs and User Agents
  • Keeps a list of connections in memory, indexed by UUIDs
  • Automatically decode non-binary messages into strings

Usage

import{WebsocketServer}from'@dimensionalpocket/websocket-server'constwebsocketServer=newWebsocketServer()websocketServer.on('connect',(connection)=>{// Connection is also available in server.connections.get("connection-uuid")console.log('Connected',connection.uuid,'on server',connection.server.uuid)})websocketServer.on('message',(connection,message,isBinary)=>{// If `isBinary` is false, then message will be a string, otherwise an ArrayBufferconsole.log('Server',connection.server.uuid,'received message',message,'from connection',connection.uuid)})websocketServer.on('disconnect',(connection,code,message)=>{// At this point the connection is no longer available in server.connections.get(...)// Connection can no longer be usedconsole.log('Disconnected',connection.uuid,'from server',connection.server.uuid,code,message)})websocketServer.on('start',(server)=>{console.log('Server',server.uuid,'now listening on host',server.host,'port',server.port)})websocketServer.on('stop',(server)=>{console.log('Server',server.uuid,'stopped')})websocketServer.start()// Sending a message to a connectionconstconnection=websocketServer.connections.get('connection-uuid')connection.send('test message')// Subscribe to a topicconnection.subscribe('some-topic')// Broadcast to a topicwebsocketServer.publish('some-topic','some message')// Close the connectionconnection.close()// Stop the server, dropping all connectionswebsocketServer.stop()

License

MIT

About

Opinionated wrapper on µWebSockets.js

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages