server.gd 870 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. extends Node
  2. # The port we will listen to.
  3. const PORT = 9080
  4. var tcp_server := TCPServer.new()
  5. var socket := WebSocketPeer.new()
  6. func log_message(message):
  7. var time = "[color=#aaaaaa] %s [/color]" % Time.get_time_string_from_system()
  8. %TextServer.text += time + message + "\n"
  9. func _ready():
  10. if tcp_server.listen(PORT) != OK:
  11. log_message("Unable to start server.")
  12. set_process(false)
  13. func _process(_delta):
  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():
  23. socket.close()
  24. tcp_server.stop()
  25. func _on_button_pong_pressed():
  26. socket.send_text("Pong")