Skip to content
ws-json adds a little abstraction to websocket
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.

ws-json-server adds a little abstraction to websocket

EventEmitter like API for WebSocket, in server-side.


Get package via npm:

npm install ws-json-server
server = require 'ws-json-server'

server.listen 3000, (ws) ->

  ws.on 'greet', (data, res) ->
    console.log 'cient sent:', data
    res 'hello client'

  ws.emit 'welcome', 'websocket', (data) ->
    console.log 'client returns:', data

  ws.on "repeat", (data, res) ->
    setTimeout (-> res (data + 1)), 2000
    console.log "repeat", data

  ws.onclose ->
    console.log 'connect closed'

  ws.emit "repeat", 1


Start server:

  • server.listen(port).each: (ws) ->

Communication is based on [key, value, id]:

  • ws.emit: key, value, (data) ->, data is what client callbacked, both value and data are optional.

  • ws.on: key, (value, res) ->, res can be used like res 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.


Read for more.


  • 0.0.6

    • Fix mutiple listeners on the same event name
Something went wrong with that request. Please try again.