WebsocketCommunicator.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. export class WebsocketCommunicator {
  2. constructor() {
  3. this.websocketConnectionString = "";
  4. this.socket = null;
  5. this.subscribedReceivers = [];
  6. }
  7. connect() {
  8. return new Promise((success, fail) => {
  9. let websocketProtocol = window.location.protocol == "https:" ? "wss:" : "ws:"
  10. let websocketPort = window.location.port != "" ? `:${window.location.port}` : ""
  11. this.websocketConnectionString = `${websocketProtocol}//${window.location.hostname}${websocketPort}/ws`
  12. this.socket = new WebSocket(this.websocketConnectionString)
  13. this.socket.onmessage = (event) => {
  14. this.handleServerMessage(event.data)
  15. }
  16. this.socket.onerror = (event) => {
  17. this.isConnected = false
  18. fail()
  19. }
  20. this.socket.onopen = (event) => {
  21. this.isConnected = true
  22. success(this.socket)
  23. }
  24. this.socket.onclose = (event) => {
  25. this.isConnected = false
  26. this.handleClose()
  27. }
  28. })
  29. }
  30. subscribe(websocketReceiver) {
  31. this.subscribedReceivers.push(websocketReceiver)
  32. }
  33. unsubscribe(websocketReceiver) {
  34. this.subscribedReceivers.splice(this.subscribedReceivers.indexOf(websocketReceiver), 1)
  35. }
  36. send(data) {
  37. var sendData = data;
  38. if (typeof data == "object") {
  39. sendData = JSON.stringify(data);
  40. }
  41. this.sendRaw(sendData)
  42. }
  43. sendRaw(data) {
  44. if (!this.isConnected || this.socket == null) {
  45. console.warn("trying to send message before socket is connected")
  46. return;
  47. }
  48. this.socket.send(data)
  49. }
  50. disconnect() {
  51. if (this.socket == null) {
  52. return;
  53. }
  54. this.socket.close();
  55. this.socket = null;
  56. }
  57. handleServerMessage(socketMessage) {
  58. for (let i = 0; i < this.subscribedReceivers.length; i++) {
  59. this.subscribedReceivers[i].handleMessage(socketMessage)
  60. }
  61. }
  62. handleClose() {
  63. for (let i = 0; i < this.subscribedReceivers.length; i++) {
  64. this.subscribedReceivers[i].handleClose()
  65. }
  66. }
  67. }