websocket.rst 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. :article_outdated: True
  2. .. _doc_websocket:
  3. WebSocket
  4. =========
  5. HTML5 and WebSocket
  6. -------------------
  7. The WebSocket protocol was standardized in 2011 with the original goal of allowing browsers to create stable and bidirectional connections with a server.
  8. Before that, browsers used to only support HTTPRequests, which is not well-suited for bidirectional communication.
  9. The protocol is message based and a very powerful tool to send push notifications to browsers, and has been used to implement chats, turn-based games, etc. It still uses a TCP connection, which is good for reliability but not for latency, so not good for real-time applications like VoIP and fast-paced games (see :ref:`WebRTC <doc_webrtc>` for those use cases).
  10. Due to its simplicity, its wide compatibility, and being easier to use than a raw TCP connection, WebSocket soon started to spread outside the browsers, in native applications as a mean to communicate with network servers.
  11. Godot supports WebSocket in both native and HTML5 exports.
  12. Using WebSocket in Godot
  13. ------------------------
  14. WebSocket is implemented in Godot via :ref:`WebSocketPeer <class_WebSocketPeer>`. The WebSocket implementation is compatible with the High Level Multiplayer. See section on :ref:`high-level multiplayer <doc_high_level_multiplayer>` for more details.
  15. .. warning::
  16. When exporting to Android, make sure to enable the ``INTERNET``
  17. permission in the Android export preset before exporting the project or
  18. using one-click deploy. Otherwise, network communication of any kind will be
  19. blocked by Android.
  20. Minimal client example
  21. ^^^^^^^^^^^^^^^^^^^^^^
  22. This example will show you how to create a WebSocket connection to a remote server, and how to send and receive data.
  23. ::
  24. extends Node
  25. # The URL we will connect to.
  26. @export var websocket_url = "wss://echo.websocket.org"
  27. # Our WebSocketClient instance.
  28. var socket = WebSocketPeer.new()
  29. func _ready():
  30. # Initiate connection to the given URL.
  31. var err = socket.connect_to_url(websocket_url)
  32. if err != OK:
  33. print("Unable to connect")
  34. set_process(false)
  35. else:
  36. # Wait for the socket to connect.
  37. await get_tree().create_timer(2).timeout
  38. # Send data.
  39. socket.send_text("Test packet")
  40. func _process(_delta):
  41. # Call this in _process or _physics_process. Data transfer and state updates
  42. # will only happen when calling this function.
  43. socket.poll()
  44. # get_ready_state() tells you what state the socket is in.
  45. var state = socket.get_ready_state()
  46. # WebSocketPeer.STATE_OPEN means the socket is connected and ready
  47. # to send and receive data.
  48. if state == WebSocketPeer.STATE_OPEN:
  49. while socket.get_available_packet_count():
  50. print("Got data from server: ", socket.get_packet().get_string_from_utf8())
  51. # WebSocketPeer.STATE_CLOSING means the socket is closing.
  52. # It is important to keep polling for a clean close.
  53. elif state == WebSocketPeer.STATE_CLOSING:
  54. pass
  55. # WebSocketPeer.STATE_CLOSED means the connection has fully closed.
  56. # It is now safe to stop polling.
  57. elif state == WebSocketPeer.STATE_CLOSED:
  58. # The code will be -1 if the disconnection was not properly notified by the remote peer.
  59. var code = socket.get_close_code()
  60. print("WebSocket closed with code: %d. Clean: %s" % [code, code != -1])
  61. set_process(false) # Stop processing.
  62. This will print something similar to:
  63. ::
  64. Got data from server: Request served by 7811941c69e658
  65. Got data from server: Test packet
  66. Minimal server example
  67. ^^^^^^^^^^^^^^^^^^^^^^
  68. This example will show you how to create a WebSocket server that listens for remote connections, and how to send and receive data.
  69. ::
  70. extends Node
  71. # The port we will listen to
  72. const PORT = 9080
  73. # Our WebSocketServer instance
  74. var _server = WebSocketServer.new()
  75. func _ready():
  76. # Connect base signals to get notified of new client connections,
  77. # disconnections, and disconnect requests.
  78. _server.client_connected.connect(_connected)
  79. _server.client_disconnected.connect(_disconnected)
  80. _server.client_close_request.connect(_close_request)
  81. # This signal is emitted when not using the Multiplayer API every time a
  82. # full packet is received.
  83. # Alternatively, you could check get_peer(PEER_ID).get_available_packets()
  84. # in a loop for each connected peer.
  85. _server.data_received.connect(_on_data)
  86. # Start listening on the given port.
  87. var err = _server.listen(PORT)
  88. if err != OK:
  89. print("Unable to start server")
  90. set_process(false)
  91. func _connected(id, proto):
  92. # This is called when a new peer connects, "id" will be the assigned peer id,
  93. # "proto" will be the selected WebSocket sub-protocol (which is optional)
  94. print("Client %d connected with protocol: %s" % [id, proto])
  95. func _close_request(id, code, reason):
  96. # This is called when a client notifies that it wishes to close the connection,
  97. # providing a reason string and close code.
  98. print("Client %d disconnecting with code: %d, reason: %s" % [id, code, reason])
  99. func _disconnected(id, was_clean = false):
  100. # This is called when a client disconnects, "id" will be the one of the
  101. # disconnecting client, "was_clean" will tell you if the disconnection
  102. # was correctly notified by the remote peer before closing the socket.
  103. print("Client %d disconnected, clean: %s" % [id, str(was_clean)])
  104. func _on_data(id):
  105. # Print the received packet, you MUST always use get_peer(id).get_packet to receive data,
  106. # and not get_packet directly when not using the MultiplayerAPI.
  107. var pkt = _server.get_peer(id).get_packet()
  108. print("Got data from client %d: %s ... echoing" % [id, pkt.get_string_from_utf8()])
  109. _server.get_peer(id).put_packet(pkt)
  110. func _process(delta):
  111. # Call this in _process or _physics_process.
  112. # Data transfer, and signals emission will only happen when calling this function.
  113. _server.poll()
  114. This will print (when a client connects) something similar to this:
  115. ::
  116. Client 1348090059 connected with protocol: selected-protocol
  117. Got data from client 1348090059: Test packet ... echoing
  118. Advanced chat demo
  119. ^^^^^^^^^^^^^^^^^^
  120. A more advanced chat demo which optionally uses the multiplayer mid-level abstraction and a high level multiplayer demo are available in the `godot demo projects <https://github.com/godotengine/godot-demo-projects>`_ under `networking/websocket_chat` and `networking/websocket_multiplayer`.