server.gd 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. extends Control
  2. @onready var _server: WebSocketServer = $WebSocketServer
  3. @onready var _log_dest = $Panel/VBoxContainer/RichTextLabel
  4. @onready var _line_edit = $Panel/VBoxContainer/Send/LineEdit
  5. @onready var _listen_port = $Panel/VBoxContainer/Connect/Port
  6. func info(msg):
  7. print(msg)
  8. _log_dest.add_text(str(msg) + "\n")
  9. # Server signals
  10. func _on_web_socket_server_client_connected(peer_id):
  11. var peer: WebSocketPeer = _server.peers[peer_id]
  12. info("Remote client connected: %d. Protocol: %s" % [peer_id, peer.get_selected_protocol()])
  13. _server.send(-peer_id, "[%d] connected" % peer_id)
  14. func _on_web_socket_server_client_disconnected(peer_id):
  15. var peer: WebSocketPeer = _server.peers[peer_id]
  16. info("Remote client disconnected: %d. Code: %d, Reason: %s" % [peer_id, peer.get_close_code(), peer.get_close_reason()])
  17. _server.send(-peer_id, "[%d] disconnected" % peer_id)
  18. func _on_web_socket_server_message_received(peer_id, message):
  19. info("Server received data from peer %d: %s" % [peer_id, message])
  20. _server.send(-peer_id, "[%d] Says: %s" % [peer_id, message])
  21. # UI signals.
  22. func _on_send_pressed():
  23. if _line_edit.text == "":
  24. return
  25. info("Sending message: %s" % [_line_edit.text])
  26. _server.send(0, "Server says: %s" % _line_edit.text)
  27. _line_edit.text = ""
  28. func _on_listen_toggled(pressed):
  29. if not pressed:
  30. _server.stop()
  31. info("Server stopped")
  32. return
  33. var port = int(_listen_port.value)
  34. var err = _server.listen(port)
  35. if err != OK:
  36. info("Error listing on port %s" % port)
  37. return
  38. info("Listing on port %s, supported protocols: %s" % [port, _server.supported_protocols])