zeronet-uiserver
Version:
ZeroNet ui and uiserver
96 lines (70 loc) • 1.91 kB
text/coffeescript
class ZeroWebsocket
constructor: (url) ->
= url
= 1
= {}
init: ->
@
connect: ->
= new WebSocket()
.onmessage =
.onopen =
.onerror =
.onclose =
= false
= []
onMessage: (e) =>
message = JSON.parse(e.data)
cmd = message.cmd
if cmd == "response"
if [message.to]?
[message.to](message.result)
else
"Websocket callback not found:", message
else if cmd == "ping"
message.id, "pong"
else
cmd, message
route: (cmd, message) =>
"Unknown command", message
response: (to, result) ->
{"cmd": "response", "to": to, "result": result}
cmd: (cmd, params={}, cb=null) ->
{"cmd": cmd, "params": params}, cb
send: (message, cb=null) ->
if not message.id?
message.id =
+= 1
if
.send(JSON.stringify(message))
else
"Not connected, adding message to queue"
.push(message)
if cb
[message.id] = cb
log: (args...) =>
console.log "[ZeroWebsocket]", args...
onOpenWebsocket: (e) =>
"Open"
= true
# Process messages sent before websocket opened
for message in
.send(JSON.stringify(message))
= []
if ? then
onErrorWebsocket: (e) =>
"Error", e
if ? then
onCloseWebsocket: (e, reconnect=10000) =>
"Closed", e
= false
if e and e.code == 1000 and e.wasClean == false
"Server error, please reload the page", e.wasClean
else # Connection error
setTimeout (=>
"Reconnecting..."
), reconnect
if ? then
window.ZeroWebsocket = ZeroWebsocket