client.gd 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. extends Node
  2. # The URL we will connect to.
  3. export var websocket_url = "ws://localhost:9080"
  4. # Our WebSocketClient instance.
  5. var _client = WebSocketClient.new()
  6. func _ready():
  7. # Connect base signals to get notified of connection open, close, and errors.
  8. _client.connect("connection_closed", self, "_closed")
  9. _client.connect("connection_error", self, "_closed")
  10. _client.connect("connection_established", self, "_connected")
  11. # This signal is emitted when not using the Multiplayer API every time
  12. # a full packet is received.
  13. # Alternatively, you could check get_peer(1).get_available_packets() in a loop.
  14. _client.connect("data_received", self, "_on_data")
  15. # Initiate connection to the given URL.
  16. var err = _client.connect_to_url(websocket_url)
  17. if err != OK:
  18. print("Unable to connect")
  19. set_process(false)
  20. func _closed(was_clean = false):
  21. # was_clean will tell you if the disconnection was correctly notified
  22. # by the remote peer before closing the socket.
  23. print("Closed, clean: ", was_clean)
  24. set_process(false)
  25. func _connected(proto = ""):
  26. # This is called on connection, "proto" will be the selected WebSocket
  27. # sub-protocol (which is optional)
  28. print("Connected with protocol: ", proto)
  29. # You MUST always use get_peer(1).put_packet to send data to server,
  30. # and not put_packet directly when not using the MultiplayerAPI.
  31. _client.get_peer(1).put_packet("Test packet".to_utf8())
  32. func _on_data():
  33. # Print the received packet, you MUST always use get_peer(1).get_packet
  34. # to receive data from server, and not get_packet directly when not
  35. # using the MultiplayerAPI.
  36. print("Got data from server: ", _client.get_peer(1).get_packet().get_string_from_utf8())
  37. func _process(_delta):
  38. # Call this in _process or _physics_process. Data transfer, and signals
  39. # emission will only happen when calling this function.
  40. _client.poll()
  41. func _exit_tree():
  42. _client.disconnect_from_host()