Skip to content

Instantly share code, notes, and snippets.

@maccman
Created May 18, 2011 14:12
Show Gist options
  • Select an option

  • Save maccman/978644 to your computer and use it in GitHub Desktop.

Select an option

Save maccman/978644 to your computer and use it in GitHub Desktop.
class WebSocketRPC
constructor: (host) ->
@callbacks = {}
@id = 0
@socket = new WebSocket(host)
@socket.onopen = @onopen
@socket.onmessage = @onmessage
@socket.onclose = @onclose
onopen: =>
onclose: =>
onmessage: (data) =>
message = JSON.parse(data)
@callbacks[message.id]?(message.result)
rpc: (method, args...) =>
id = @id += 1
if typeof args[args.length - 1] == "function"
callback = args.pop()
@callbacks[id] = callback if callback
message =
id: id,
method: method,
args: args
@socket.send(JSON.stringify(message))
# Result:
# => {"method": "ga", "args": ["ga1", "ga2"], "id": 1}
# <= {"id": 1, "result": "blah"}
@maccman
Copy link
Copy Markdown
Author

maccman commented May 18, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment