add extended JSON subprotocol support

This commit is contained in:
mattx 2020-06-23 20:39:11 +02:00
parent 33d1bef1e6
commit 73de73c9ca
2 changed files with 53 additions and 18 deletions

View File

@ -20,24 +20,58 @@ removeElement = (array, elem) ->
index = array.indexOf(elem)
array.splice(index, 1) if index > -1
broadcastCounter = ->
sockets.forEach (socket) ->
socket.send counter
makeHelloMsg = ->
return {
event: "hello",
features: [],
count: counter
}
app.ws "/api", (ws, req) ->
ws.send counter
sockets.push ws
makeCountMsg = ->
return {
event: "countUpdate",
count: counter
}
broadcastCounter = ->
msg = makeCountMsg()
sockets.forEach (socket) ->
switch socket.protocol
when "incdec" then socket.send counter
when "extended-json" then socket.send JSON.stringify(msg)
else socket.send counter
setupExtendedSocket = (ws) ->
ws.send JSON.stringify(makeHelloMsg())
ws.on "message", (msg) ->
switch
when msg=="inc"
counter = counter + 1
when msg=="dec"
counter = counter - 1
data = JSON.parse(msg)
switch data.event
when "increment" then counter = counter + 1
when "decrement" then counter = counter - 1
else
errored = true
ws.close
broadcastCounter() if not errored
ws.on "close", -> removeElement sockets, ws
setupSocket = (ws) ->
ws.send counter
ws.on "message", (msg) ->
switch msg
when "inc" then counter = counter + 1
when "dec" then counter = counter - 1
else
errored = true
ws.send "err"
broadcastCounter() if not errored
ws.on "close", -> removeElement sockets, ws
app.ws "/api", (ws, req) ->
sockets.push ws
switch ws.protocol
when "incdec" then setupSocket(ws)
when "extended-json" then setupExtendedSocket(ws)
else setupSocket(ws)
app.listen config.port, () ->
console.log("ready on port " + config.port)

View File

@ -1,12 +1,13 @@
window.addEventListener "DOMContentLoaded", (event) ->
window.socket = new WebSocket(location.origin.replace(/^http/, "ws") + "/api")
window.socket = new WebSocket(location.origin.replace(/^http/, "ws") + "/api", "extended-json")
counter = document.getElementById "counter"
socket.addEventListener "message", (event) ->
if event.data == "err"
alert "error occured"
else
counter.innerText = event.data
data = JSON.parse(event.data);
switch data.event
when "hello" then counter.innerText = data.count
when "countUpdate" then counter.innerText = data.count
else alert "unknown event"
increment = -> socket.send("inc")
decrement = -> socket.send("dec")
increment = -> socket.send(JSON.stringify({"event": "increment"}))
decrement = -> socket.send(JSON.stringify({"event": "decrement"}))