websocket.rst 6.9 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://libwebsockets.org"
  27. # Our WebSocketClient instance
  28. var _client = WebSocketClient.new()
  29. func _ready():
  30. # Connect base signals to get notified of connection open, close, and errors.
  31. _client.connection_closed.connect(_closed)
  32. _client.connection_error.connect(_closed)
  33. _client.connection_established.connect(_connected)
  34. # This signal is emitted when not using the Multiplayer API every time
  35. # a full packet is received.
  36. # Alternatively, you could check get_peer(1).get_available_packets() in a loop.
  37. _client.data_received.connect(_on_data)
  38. # Initiate connection to the given URL.
  39. var err = _client.connect_to_url(websocket_url, ["lws-mirror-protocol"])
  40. if err != OK:
  41. print("Unable to connect")
  42. set_process(false)
  43. func _closed(was_clean = false):
  44. # was_clean will tell you if the disconnection was correctly notified
  45. # by the remote peer before closing the socket.
  46. print("Closed, clean: ", was_clean)
  47. set_process(false)
  48. func _connected(proto = ""):
  49. # This is called on connection, "proto" will be the selected WebSocket
  50. # sub-protocol (which is optional)
  51. print("Connected with protocol: ", proto)
  52. # You MUST always use get_peer(1).put_packet to send data to server,
  53. # and not put_packet directly when not using the MultiplayerAPI.
  54. _client.get_peer(1).put_packet("Test packet".to_utf8())
  55. func _on_data():
  56. # Print the received packet, you MUST always use get_peer(1).get_packet
  57. # to receive data from server, and not get_packet directly when not
  58. # using the MultiplayerAPI.
  59. print("Got data from server: ", _client.get_peer(1).get_packet().get_string_from_utf8())
  60. func _process(delta):
  61. # Call this in _process or _physics_process. Data transfer, and signals
  62. # emission will only happen when calling this function.
  63. _client.poll()
  64. This will print:
  65. ::
  66. Connected with protocol:
  67. Got data from server: Test packet
  68. Minimal server example
  69. ^^^^^^^^^^^^^^^^^^^^^^
  70. This example will show you how to create a WebSocket server that listens for remote connections, and how to send and receive data.
  71. ::
  72. extends Node
  73. # The port we will listen to
  74. const PORT = 9080
  75. # Our WebSocketServer instance
  76. var _server = WebSocketServer.new()
  77. func _ready():
  78. # Connect base signals to get notified of new client connections,
  79. # disconnections, and disconnect requests.
  80. _server.client_connected.connect(_connected)
  81. _server.client_disconnected.connect(_disconnected)
  82. _server.client_close_request.connect(_close_request)
  83. # This signal is emitted when not using the Multiplayer API every time a
  84. # full packet is received.
  85. # Alternatively, you could check get_peer(PEER_ID).get_available_packets()
  86. # in a loop for each connected peer.
  87. _server.data_received.connect(_on_data)
  88. # Start listening on the given port.
  89. var err = _server.listen(PORT)
  90. if err != OK:
  91. print("Unable to start server")
  92. set_process(false)
  93. func _connected(id, proto):
  94. # This is called when a new peer connects, "id" will be the assigned peer id,
  95. # "proto" will be the selected WebSocket sub-protocol (which is optional)
  96. print("Client %d connected with protocol: %s" % [id, proto])
  97. func _close_request(id, code, reason):
  98. # This is called when a client notifies that it wishes to close the connection,
  99. # providing a reason string and close code.
  100. print("Client %d disconnecting with code: %d, reason: %s" % [id, code, reason])
  101. func _disconnected(id, was_clean = false):
  102. # This is called when a client disconnects, "id" will be the one of the
  103. # disconnecting client, "was_clean" will tell you if the disconnection
  104. # was correctly notified by the remote peer before closing the socket.
  105. print("Client %d disconnected, clean: %s" % [id, str(was_clean)])
  106. func _on_data(id):
  107. # Print the received packet, you MUST always use get_peer(id).get_packet to receive data,
  108. # and not get_packet directly when not using the MultiplayerAPI.
  109. var pkt = _server.get_peer(id).get_packet()
  110. print("Got data from client %d: %s ... echoing" % [id, pkt.get_string_from_utf8()])
  111. _server.get_peer(id).put_packet(pkt)
  112. func _process(delta):
  113. # Call this in _process or _physics_process.
  114. # Data transfer, and signals emission will only happen when calling this function.
  115. _server.poll()
  116. This will print (when a client connects) something similar to this:
  117. ::
  118. Client 1348090059 connected with protocol: selected-protocol
  119. Got data from client 1348090059: Test packet ... echoing
  120. Advanced chat demo
  121. ^^^^^^^^^^^^^^^^^^
  122. 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`.