ws-json-server adds a little abstraction to websocket
EventEmitter like API for WebSocket, in server-side.
Usage
Get package via npm:
npm install ws-json-server
server = require 'ws-json-server' serverlisten 3000 wson 'greet' consolelog 'cient sent:'data res 'hello client' wsemit 'welcome''websocket' consolelog 'client returns:'data wson "repeat" setTimeout -> res data + 12000 consolelog "repeat"data wsonclose -> consolelog 'connect closed' wsemit "repeat"1
API
Start server:
server.listen(port).each
:(ws) ->
Communication is based on [key, value, id]
:
-
ws.emit
:key, value, (data) ->
,data
is what client callbacked, bothvalue
and data are optional. -
ws.on
:key, (value, res) ->
,res
can be used likeres value
to send data back
When close:
ws.onclose
:->
ws.closed
Since there might be lots of connections and many instances of ws
.
ws
objects may fail to be garbage collected.
To stay away from memory leak, a solution from Backbone.
-
ws.listenTo
:source, eventName, (value) ->
, it uses.removeListener()
internally -
ws.join
:room
-
ws.leave
:room
To join and leave room which is represented in string.
ws.broadcast
:key, value
ws.cast
:room, key, value
Broadcast message in rooms and in a specified room.
ws.bind
:(key, value) ->
Listen events from broadcast and activate a callback.
Development
Read make.coffee
for more.
Changelog
-
0.0.6
- Fix mutiple listeners on the same event name