websocket-observer
v1.0.0
Published
Basically an observer pattern that notifies the clients subscribed
Downloads
2
Readme
WebsocketObserver
Basically an observer pattern that notifies the clients subscribed
Usage Example
const WebSocket = require('ws')
const Observer = require('websocket-observer')
const wss = new WebSocket.Server({ port: 3000 })
Observer.setData('')
wss.on('connection', client => {
Observer.subscribe(client)
client.on('message', msg => Observer.setData(data => `${ data }, ${ msg }`))
})
Methods
subscribe
Saves the client, sets him up to unsusbribe on disconnection and notifies him
setData
Updates the data saved by the observer and broadcasts it to all clients
Can either receive a value(any type)
Observer.setData({
msg: 'Message'
}))
Or a function which receives the current data as paremeter and returns the updated data
Observer.setData(data => data + msg))
getData
Returns the data
getSubscribers
Returns the subscribers