server.gd 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. extends Node
  2. # The port we will listen to.
  3. const PORT = 9080
  4. # Our WebSocketServer instance.
  5. var _server = WebSocketServer.new()
  6. func _ready():
  7. # Connect base signals to get notified of new client connections,
  8. # disconnections, and disconnect requests.
  9. _server.connect("client_connected", self, "_connected")
  10. _server.connect("client_disconnected", self, "_disconnected")
  11. _server.connect("client_close_request", self, "_close_request")
  12. # This signal is emitted when not using the Multiplayer API every time a
  13. # full packet is received.
  14. # Alternatively, you could check get_peer(PEER_ID).get_available_packets()
  15. # in a loop for each connected peer.
  16. _server.connect("data_received", self, "_on_data")
  17. # Start listening on the given port.
  18. var err = _server.listen(PORT)
  19. if err != OK:
  20. print("Unable to start server")
  21. set_process(false)
  22. func _connected(id, proto):
  23. # This is called when a new peer connects, "id" will be the assigned peer id,
  24. # "proto" will be the selected WebSocket sub-protocol (which is optional)
  25. print("Client %d connected with protocol: %s" % [id, proto])
  26. func _close_request(id, code, reason):
  27. # This is called when a client notifies that it wishes to close the connection,
  28. # providing a reason string and close code.
  29. print("Client %d disconnecting with code: %d, reason: %s" % [id, code, reason])
  30. func _disconnected(id, was_clean = false):
  31. # This is called when a client disconnects, "id" will be the one of the
  32. # disconnecting client, "was_clean" will tell you if the disconnection
  33. # was correctly notified by the remote peer before closing the socket.
  34. print("Client %d disconnected, clean: %s" % [id, str(was_clean)])
  35. func _on_data(id):
  36. # Print the received packet, you MUST always use get_peer(id).get_packet to receive data,
  37. # and not get_packet directly when not using the MultiplayerAPI.
  38. var pkt = _server.get_peer(id).get_packet()
  39. print("Got data from client %d: %s ... echoing" % [id, pkt.get_string_from_utf8()])
  40. _server.get_peer(id).put_packet(pkt)
  41. func _process(_delta):
  42. # Call this in _process or _physics_process.
  43. # Data transfer, and signals emission will only happen when calling this function.
  44. _server.poll()
  45. func _exit_tree():
  46. _server.stop()