websocket.rst 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. .. _doc_websocket:
  2. WebSocket
  3. =========
  4. HTML5 and WebSocket
  5. -------------------
  6. The WebSocket protocol was standardized in 2011 with the original goal of allowing browsers to create stable and bidirectional connections with a server.
  7. Before that, browsers used to only support HTTPRequests, which is not well-suited for bidirectional communication.
  8. The protocol is quite simple, 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).
  9. 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.
  10. Godot supports WebSocket in both native and HTML5 exports.
  11. Using WebSocket in Godot
  12. ------------------------
  13. WebSocket is implemented in Godot via three main classes :ref:`WebSocketClient <class_WebSocketClient>`, :ref:`WebSocketServer <class_WebSocketServer>`, and :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.
  14. .. warning::
  15. When exporting to Android, make sure to enable the ``INTERNET``
  16. permission in the Android export preset before exporting the project or
  17. using one-click deploy. Otherwise, network communication of any kind will be
  18. blocked by Android.
  19. Minimal client example
  20. ^^^^^^^^^^^^^^^^^^^^^^
  21. This example will show you how to create a WebSocket connection to a remote server, and how to send and receive data.
  22. ::
  23. extends Node
  24. # The URL we will connect to
  25. export var websocket_url = "wss://libwebsockets.org"
  26. # Our WebSocketClient instance
  27. var _client = WebSocketClient.new()
  28. func _ready():
  29. # Connect base signals to get notified of connection open, close, and errors.
  30. _client.connect("connection_closed", self, "_closed")
  31. _client.connect("connection_error", self, "_closed")
  32. _client.connect("connection_established", self, "_connected")
  33. # This signal is emitted when not using the Multiplayer API every time
  34. # a full packet is received.
  35. # Alternatively, you could check get_peer(1).get_available_packets() in a loop.
  36. _client.connect("data_received", self, "_on_data")
  37. # Initiate connection to the given URL.
  38. var err = _client.connect_to_url(websocket_url, ["lws-mirror-protocol"])
  39. if err != OK:
  40. print("Unable to connect")
  41. set_process(false)
  42. func _closed(was_clean = false):
  43. # was_clean will tell you if the disconnection was correctly notified
  44. # by the remote peer before closing the socket.
  45. print("Closed, clean: ", was_clean)
  46. set_process(false)
  47. func _connected(proto = ""):
  48. # This is called on connection, "proto" will be the selected WebSocket
  49. # sub-protocol (which is optional)
  50. print("Connected with protocol: ", proto)
  51. # You MUST always use get_peer(1).put_packet to send data to server,
  52. # and not put_packet directly when not using the MultiplayerAPI.
  53. _client.get_peer(1).put_packet("Test packet".to_utf8())
  54. func _on_data():
  55. # Print the received packet, you MUST always use get_peer(1).get_packet
  56. # to receive data from server, and not get_packet directly when not
  57. # using the MultiplayerAPI.
  58. print("Got data from server: ", _client.get_peer(1).get_packet().get_string_from_utf8())
  59. func _process(delta):
  60. # Call this in _process or _physics_process. Data transfer, and signals
  61. # emission will only happen when calling this function.
  62. _client.poll()
  63. This will print:
  64. ::
  65. Connected with protocol:
  66. Got data from server: Test packet
  67. Minimal server example
  68. ^^^^^^^^^^^^^^^^^^^^^^
  69. This example will show you how to create a WebSocket server that listens for remote connections, and how to send and receive data.
  70. ::
  71. extends Node
  72. # The port we will listen to
  73. const PORT = 9080
  74. # Our WebSocketServer instance
  75. var _server = WebSocketServer.new()
  76. func _ready():
  77. # Connect base signals to get notified of new client connections,
  78. # disconnections, and disconnect requests.
  79. _server.connect("client_connected", self, "_connected")
  80. _server.connect("client_disconnected", self, "_disconnected")
  81. _server.connect("client_close_request", self, "_close_request")
  82. # This signal is emitted when not using the Multiplayer API every time a
  83. # full packet is received.
  84. # Alternatively, you could check get_peer(PEER_ID).get_available_packets()
  85. # in a loop for each connected peer.
  86. _server.connect("data_received", self, "_on_data")
  87. # Start listening on the given port.
  88. var err = _server.listen(PORT)
  89. if err != OK:
  90. print("Unable to start server")
  91. set_process(false)
  92. func _connected(id, proto):
  93. # This is called when a new peer connects, "id" will be the assigned peer id,
  94. # "proto" will be the selected WebSocket sub-protocol (which is optional)
  95. print("Client %d connected with protocol: %s" % [id, proto])
  96. func _close_request(id, code, reason):
  97. # This is called when a client notifies that it wishes to close the connection,
  98. # providing a reason string and close code.
  99. print("Client %d disconnecting with code: %d, reason: %s" % [id, code, reason])
  100. func _disconnected(id, was_clean = false):
  101. # This is called when a client disconnects, "id" will be the one of the
  102. # disconnecting client, "was_clean" will tell you if the disconnection
  103. # was correctly notified by the remote peer before closing the socket.
  104. print("Client %d disconnected, clean: %s" % [id, str(was_clean)])
  105. func _on_data(id):
  106. # Print the received packet, you MUST always use get_peer(id).get_packet to receive data,
  107. # and not get_packet directly when not using the MultiplayerAPI.
  108. var pkt = _server.get_peer(id).get_packet()
  109. print("Got data from client %d: %s ... echoing" % [id, pkt.get_string_from_utf8()])
  110. _server.get_peer(id).put_packet(pkt)
  111. func _process(delta):
  112. # Call this in _process or _physics_process.
  113. # Data transfer, and signals emission will only happen when calling this function.
  114. _server.poll()
  115. This will print (when a client connects) something similar to this:
  116. ::
  117. Client 1348090059 connected with protocol: selected-protocol
  118. Got data from client 1348090059: Test packet ... echoing
  119. Advanced chat demo
  120. ^^^^^^^^^^^^^^^^^^
  121. 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`.