websocket.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. window.ws = null
  2. export function checkWebsocketConnection () {
  3. if (window.ws === null || window.ws.readyState === 3) {
  4. reconnectWebsocket()
  5. }
  6. }
  7. function reconnectWebsocket () {
  8. window.websocketAvailable = false
  9. let proto = 'ws:'
  10. if (window.location.protocol === 'https:') {
  11. proto = 'wss:'
  12. }
  13. const websocketConnectionUrl = proto + window.location.host + '/websocket'
  14. const ws = window.ws = new WebSocket(websocketConnectionUrl)
  15. ws.addEventListener('open', websocketOnOpen)
  16. ws.addEventListener('message', websocketOnMessage)
  17. ws.addEventListener('error', websocketOnError)
  18. ws.addEventListener('close', websocketOnClose)
  19. }
  20. function websocketOnOpen (evt) {
  21. window.websocketAvailable = true
  22. window.ws.send('monitor')
  23. window.refreshLoop()
  24. }
  25. function websocketOnMessage (msg) {
  26. // FIXME check msg status is OK
  27. const j = JSON.parse(msg.data)
  28. const e = new Event(j.type)
  29. e.payload = j.payload
  30. switch (j.type) {
  31. case 'ExecutionFinished':
  32. window.dispatchEvent(e)
  33. break
  34. default:
  35. window.showBigError('Unknown message type from server: ' + j.type)
  36. }
  37. }
  38. function websocketOnError (err) {
  39. window.websocketAvailable = false
  40. window.refreshLoop()
  41. console.error(err)
  42. }
  43. function websocketOnClose () {
  44. window.websocketAvailable = false
  45. }