WebSocketClient.gd 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. extends Node
  2. class_name WebSocketClient
  3. @export var handshake_headers: PackedStringArray
  4. @export var supported_protocols: PackedStringArray
  5. var tls_options: TLSOptions = null
  6. var socket = WebSocketPeer.new()
  7. var last_state = WebSocketPeer.STATE_CLOSED
  8. signal connected_to_server()
  9. signal connection_closed()
  10. signal message_received(message: Variant)
  11. func connect_to_url(url) -> int:
  12. socket.supported_protocols = supported_protocols
  13. socket.handshake_headers = handshake_headers
  14. var err = socket.connect_to_url(url, tls_options)
  15. if err != OK:
  16. return err
  17. last_state = socket.get_ready_state()
  18. return OK
  19. func send(message) -> int:
  20. if typeof(message) == TYPE_STRING:
  21. return socket.send_text(message)
  22. return socket.send(var_to_bytes(message))
  23. func get_message() -> Variant:
  24. if socket.get_available_packet_count() < 1:
  25. return null
  26. var pkt = socket.get_packet()
  27. if socket.was_string_packet():
  28. return pkt.get_string_from_utf8()
  29. return bytes_to_var(pkt)
  30. func close(code := 1000, reason := "") -> void:
  31. socket.close(code, reason)
  32. last_state = socket.get_ready_state()
  33. func clear() -> void:
  34. socket = WebSocketPeer.new()
  35. last_state = socket.get_ready_state()
  36. func get_socket() -> WebSocketPeer:
  37. return socket
  38. func poll() -> void:
  39. if socket.get_ready_state() != socket.STATE_CLOSED:
  40. socket.poll()
  41. var state = socket.get_ready_state()
  42. if last_state != state:
  43. last_state = state
  44. if state == socket.STATE_OPEN:
  45. connected_to_server.emit()
  46. elif state == socket.STATE_CLOSED:
  47. connection_closed.emit()
  48. while socket.get_ready_state() == socket.STATE_OPEN and socket.get_available_packet_count():
  49. message_received.emit(get_message())
  50. func _process(delta):
  51. poll()