server.gd 937 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. extends Node
  2. ## The port the server will listen on.
  3. const PORT = 9080
  4. var tcp_server := TCPServer.new()
  5. var socket := WebSocketPeer.new()
  6. func log_message(message: String) -> void:
  7. var time := "[color=#aaaaaa] %s |[/color] " % Time.get_time_string_from_system()
  8. %TextServer.text += time + message + "\n"
  9. func _ready() -> void:
  10. if tcp_server.listen(PORT) != OK:
  11. log_message("Unable to start server.")
  12. set_process(false)
  13. func _process(_delta: float) -> void:
  14. while tcp_server.is_connection_available():
  15. var conn: StreamPeerTCP = tcp_server.take_connection()
  16. assert(conn != null)
  17. socket.accept_stream(conn)
  18. socket.poll()
  19. if socket.get_ready_state() == WebSocketPeer.STATE_OPEN:
  20. while socket.get_available_packet_count():
  21. log_message(socket.get_packet().get_string_from_ascii())
  22. func _exit_tree() -> void:
  23. socket.close()
  24. tcp_server.stop()
  25. func _on_button_pong_pressed() -> void:
  26. socket.send_text("Pong")