websocket.gd 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. extends Node
  2. signal closed
  3. signal connected
  4. # The URL we will connect to
  5. export var websocket_url = "ws://172.31.190.65:8081/ws"
  6. var receiver = {}
  7. # Our WebSocketClient instance
  8. var _client = WebSocketClient.new()
  9. func send(method = "GET", path="/", body = {}, streamid = ""):
  10. var msg = {"method": method, "path": path, "body": Marshalls.utf8_to_base64(JSON.print(body)), "streamid": streamid}
  11. var json_string = JSON.print(msg)
  12. _client.get_peer(1).put_packet(json_string.to_utf8())
  13. func reconnect(url = ""):
  14. if url:
  15. self.websocket_url = url
  16. if _client.CONNECTION_CONNECTED:
  17. return
  18. var err = _client.connect_to_url(websocket_url)
  19. if err != OK:
  20. print("Unable to connect")
  21. set_process(false)
  22. else:
  23. set_process(true)
  24. func registerReceiver(streamid : String, target):
  25. receiver[streamid] = target
  26. func _ready():
  27. # Connect base signals to get notified of connection open, close, and errors.
  28. _client.connect("connection_closed", self, "_closed")
  29. Messaging.registerPublisher("/websocket/connected", self, "connected")
  30. _client.connect("connection_error", self, "_closed")
  31. _client.connect("connection_established", self, "_connected")
  32. Messaging.registerPublisher("/websocket/closed", self, "closed")
  33. # This signal is emitted when not using the Multiplayer API every time
  34. # a full packet is received.
  35. # Alternatively, you could check get_peer(1).get_available_packets() in a loop.
  36. _client.connect("data_received", self, "_on_data")
  37. # Initiate connection to the given URL.
  38. var err = _client.connect_to_url(websocket_url)
  39. if err != OK:
  40. print("Unable to connect")
  41. set_process(false)
  42. func _closed(was_clean = false):
  43. # was_clean will tell you if the disconnection was correctly notified
  44. # by the remote peer before closing the socket.
  45. print("Closed, clean: ", was_clean)
  46. self.emit_signal("closed")
  47. set_process(false)
  48. func _connected(proto = ""):
  49. # This is called on connection, "proto" will be the selected WebSocket
  50. # sub-protocol (which is optional)
  51. print("Connected with protocol: ", proto)
  52. # You MUST always use get_peer(1).put_packet to send data to server,
  53. # and not put_packet directly when not using the MultiplayerAPI.
  54. self.emit_signal("connected")
  55. _client.get_peer(1).put_packet("Test packet".to_utf8())
  56. func _on_data():
  57. # Print the received packet, you MUST always use get_peer(1).get_packet
  58. # to receive data from server, and not get_packet directly when not
  59. # using the MultiplayerAPI.
  60. var data = _client.get_peer(1).get_packet().get_string_from_utf8()
  61. print("Got data from server: ", data)
  62. var result = JSON.parse(data)
  63. if result.error != OK:
  64. print("JSON Parse Error: ", result.get_error_string(), " in ", data, " at line ", result.get_error_line())
  65. if not result.result:
  66. return
  67. var msg = result.result
  68. match msg["method"]+":"+msg["path"]:
  69. "test:/test":
  70. print(Marshalls.base64_to_utf8(msg["body"]))
  71. "POST:/v1/point":
  72. print(Marshalls.base64_to_utf8(msg["body"]))
  73. "GET:/v1/point/1":
  74. print(Marshalls.base64_to_utf8(msg["body"]))
  75. _:
  76. if receiver.has(msg["streamid"]):
  77. receiver[msg["streamid"]].receive(msg["streamid"], Marshalls.base64_to_utf8(msg["body"]))
  78. else:
  79. print("UNMATCHED HEADER!", msg["method"]+":"+msg["path"])
  80. print(Marshalls.base64_to_utf8(msg["body"]))
  81. func _process(delta):
  82. # Call this in _process or _physics_process. Data transfer, and signals
  83. # emission will only happen when calling this function.
  84. _client.poll()