high_level_multiplayer.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. .. _doc_high_level_multiplayer:
  2. High-level multiplayer
  3. ======================
  4. High-level vs low-level API
  5. ---------------------------
  6. The following explains the differences of high- and low-level networking in Godot as well as some fundamentals. If you want to jump in head-first and add networking to your first nodes, skip to `Initializing the network`_ below. But make sure to read the rest later on!
  7. Godot always supported standard low-level networking via :abbr:`UDP (User Datagram Protocol)`, :abbr:`TCP (Transmission Control Protocol)` and some higher-level protocols such as :abbr:`HTTP (Hypertext Transfer Protocol)` and :abbr:`SSL (Secure Sockets Layer)`.
  8. These protocols are flexible and can be used for almost anything. However, using them to synchronize game state manually can be a large amount of work. Sometimes that work can't be avoided or is worth it, for example when working with a custom server implementation on the backend. But in most cases, it's worthwhile to consider Godot's high-level networking API, which sacrifices some of the fine-grained control of low-level networking for greater ease of use.
  9. This is due to the inherent limitations of the low-level protocols:
  10. - TCP ensures packets will always arrive reliably and in order, but latency is generally higher due to error correction.
  11. It's also quite a complex protocol because it understands what a "connection" is, and optimizes for goals that often don't suit applications like multiplayer games. Packets are buffered to be sent in larger batches, trading less per-packet overhead for higher latency. This can be useful for things like HTTP, but generally not for games. Some of this can be configured and disabled (e.g. by disabling "Nagle's algorithm" for the TCP connection).
  12. - UDP is a simpler protocol, which only sends packets (and has no concept of a "connection"). No error correction
  13. makes it pretty quick (low latency), but packets may be lost along the way or received in the wrong order.
  14. Added to that, the MTU (maximum packet size) for UDP is generally low (only a few hundred bytes), so transmitting
  15. larger packets means splitting them, reorganizing them and retrying if a part fails.
  16. In general, TCP can be thought of as reliable, ordered, and slow; UDP as unreliable, unordered and fast.
  17. Because of the large difference in performance, it often makes sense to re-build the parts of TCP wanted for games (optional reliability and packet order), while avoiding the unwanted parts (congestion/traffic control features, Nagle's algorithm, etc). Due to this, most game engines come with such an implementation, and Godot is no exception.
  18. In summary, you can use the low-level networking API for maximum control and implement everything on top of bare network protocols or use the high-level API based on :ref:`SceneTree <class_SceneTree>` that does most of the heavy lifting behind the scenes in a generally optimized way.
  19. .. note:: Most of Godot's supported platforms offer all or most of the mentioned high- and low-level networking
  20. features. As networking is always largely hardware and operating system dependent, however,
  21. some features may change or not be available on some target platforms. Most notably,
  22. the HTML5 platform currently offers WebSockets and WebRTC support but lacks some of the higher-level features, as
  23. well as raw access to low-level protocols like TCP and UDP.
  24. .. note:: More about TCP/IP, UDP, and networking:
  25. https://gafferongames.com/post/udp_vs_tcp/
  26. Gaffer On Games has a lot of useful articles about networking in Games
  27. (`here <https://gafferongames.com/categories/game-networking/>`__), including the comprehensive
  28. `introduction to networking models in games <https://gafferongames.com/post/what_every_programmer_needs_to_know_about_game_networking/>`__.
  29. If you want to use your low-level networking library of choice instead of Godot's built-in networking,
  30. see here for an example:
  31. https://github.com/PerduGames/gdnet3
  32. .. warning:: Adding networking to your game comes with some responsibility.
  33. It can make your application vulnerable if done wrong and may lead to cheats or exploits.
  34. It may even allow an attacker to compromise the machines your application runs on
  35. and use your servers to send spam, attack others or steal your users' data if they play your game.
  36. This is always the case when networking is involved and has nothing to do with Godot.
  37. You can of course experiment, but when you release a networked application,
  38. always take care of any possible security concerns.
  39. Mid-level abstraction
  40. ---------------------
  41. Before going into how we would like to synchronize a game across the network, it can be helpful to understand how the base network API for synchronization works.
  42. Godot uses a mid-level object :ref:`MultiplayerPeer <class_MultiplayerPeer>`.
  43. This object is not meant to be created directly, but is designed so that several C++ implementations can provide it.
  44. This object extends from :ref:`PacketPeer <class_PacketPeer>`, so it inherits all the useful methods for serializing, sending and receiving data. On top of that, it adds methods to set a peer, transfer mode, etc. It also includes signals that will let you know when peers connect or disconnect.
  45. This class interface can abstract most types of network layers, topologies and libraries. By default, Godot
  46. provides an implementation based on ENet (:ref:`ENetMultiplayerPeer <class_ENetMultiplayerPeer>`),
  47. one based on WebRTC (:ref:`WebRTCMultiplayerPeer <class_WebRTCMultiplayerPeer>`), and one based on WebSocket
  48. (:ref:`WebSocketPeer <class_WebSocketPeer>`), but this could be used to implement
  49. mobile APIs (for ad hoc WiFi, Bluetooth) or custom device/console-specific networking APIs.
  50. For most common cases, using this object directly is discouraged, as Godot provides even higher level networking facilities.
  51. This object is still made available in case a game has specific needs for a lower-level API.
  52. Hosting considerations
  53. ----------------------
  54. When hosting a server, clients on your :abbr:`LAN (Local Area Network)` can
  55. connect using the internal IP address which is usually of the form
  56. ``192.168.*.*``. This internal IP address is **not** reachable by
  57. non-LAN/Internet clients.
  58. On Windows, you can find your internal IP address by opening a command prompt
  59. and entering ``ipconfig``. On macOS, open a Terminal and enter ``ifconfig``. On
  60. Linux, open a terminal and enter ``ip addr``.
  61. If you're hosting a server on your own machine and want non-LAN clients to
  62. connect to it, you'll probably have to *forward* the server port on your router.
  63. This is required to make your server reachable from the Internet since most
  64. residential connections use a `NAT
  65. <https://en.wikipedia.org/wiki/Network_address_translation>`__. Godot's
  66. high-level multiplayer API only uses UDP, so you must forward the port in UDP,
  67. not just TCP.
  68. After forwarding an UDP port and making sure your server uses that port, you can
  69. use `this website <https://icanhazip.com/>`__ to find your public IP address.
  70. Then give this public IP address to any Internet clients that wish to connect to
  71. your server.
  72. Godot's high-level multiplayer API uses a modified version of ENet which allows
  73. for full IPv6 support.
  74. Initializing the network
  75. ------------------------
  76. High level networking in Godot is managed by the :ref:`SceneTree <class_SceneTree>`.
  77. Each node has a ``multiplayer`` property, which is a reference to the ``MultiplayerAPI`` instance configured for it
  78. by the scene tree. Initially, every node is configured with the same default ``MultiplayerAPI`` object.
  79. It is possible to create a new ``MultiplayerAPI`` object and assign it to a ``NodePath`` in the the scene tree,
  80. which will override ``multiplayer`` for the node at that path and all of its descendants.
  81. This allows sibling nodes to be configured with different peers, which makes it possible to run a server
  82. and a client simultaneously in one instance of Godot.
  83. ::
  84. # By default, these expressions are interchangeable.
  85. multiplayer # Get the MultiplayerAPI object configured for this node.
  86. get_tree().get_multiplayer() # Get the default MultiplayerAPI object.
  87. To initialize networking, a ``MultiplayerPeer`` object must be created, initialized as a server or client,
  88. and passed to the ``MultiplayerAPI``.
  89. ::
  90. # Create client.
  91. var peer = ENetMultiplayerPeer.new()
  92. peer.create_client(IP_ADDRESS, PORT)
  93. multiplayer.multiplayer_peer = peer
  94. # Create server.
  95. var peer = ENetMultiplayerPeer.new()
  96. peer.create_server(PORT, MAX_CLIENTS)
  97. multiplayer.multiplayer_peer = peer
  98. To terminate networking:
  99. ::
  100. multiplayer.multiplayer_peer = null
  101. .. warning::
  102. When exporting to Android, make sure to enable the ``INTERNET``
  103. permission in the Android export preset before exporting the project or
  104. using one-click deploy. Otherwise, network communication of any kind will be
  105. blocked by Android.
  106. Managing connections
  107. --------------------
  108. Every peer is assigned a unique ID. The server's ID is always 1, and clients are assigned a random positive integer.
  109. Responding to connections or disconnections is possible by connecting to ``MultiplayerAPI``'s signals:
  110. - ``peer_connected(id: int)`` This signal is emitted with the newly connected peer's ID on each other peer, and on the new peer multiple times, once with each other peer's ID.
  111. - ``peer_disconnected(id: int)`` This signal is emitted on every remaining peer when one disconnects.
  112. The rest are only emitted on clients:
  113. - ``connected_to_server()``
  114. - ``connection_failed()``
  115. - ``server_disconnected()``
  116. To get the unique ID of the associated peer:
  117. ::
  118. multiplayer.get_unique_id()
  119. To check whether the peer is server or client:
  120. ::
  121. multiplayer.is_server()
  122. Remote procedure calls
  123. ----------------------
  124. Remote procedure calls, or RPCs, are functions that can be called on other peers. To create one, use the ``@rpc`` annotation
  125. before a function definition. To call an RPC, use ``Callable``'s method ``rpc()`` to call in every peer, or ``rpc_id()`` to
  126. call in a specific peer.
  127. ::
  128. func _ready():
  129. if multiplayer.is_server():
  130. print_once_per_client.rpc()
  131. @rpc
  132. func print_once_per_client():
  133. print("I will be printed to the console once per each connected client.")
  134. RPCs will not serialize objects or callables.
  135. For a remote call to be successful, the sending and receiving node need to have the same ``NodePath``, which means they
  136. must have the same name. When using ``add_child()`` for nodes which are expected to use RPCs, set the argument
  137. ``force_readable_name`` to ``true``.
  138. The annotation can take a number of arguments, which have default values. ``@rpc`` is equivalent to:
  139. ::
  140. @rpc("authority", "call_remote", "unreliable", 0)
  141. The parameters and their functions are as follows:
  142. ``mode``:
  143. - ``"authority"``: Only the multiplayer authority (the server) can call remotely.
  144. - ``"any_peer"``: Clients are allowed to call remotely. Useful for transferring user input.
  145. ``sync``:
  146. - ``"call_remote"``: The function will not be called on the local peer.
  147. - ``"call_local"``: The function can be called on the local peer. Useful when the server is also a player.
  148. ``transfer_mode``:
  149. - ``"unreliable"`` Packets are not acknowledged, can be lost, and can arrive at any order.
  150. - ``"unreliable_ordered"`` Packets are received in the order they were sent in. This is achieved by ignoring packets that arrive later if another that was sent after them has already been received. Can cause packet loss if used incorrectly.
  151. - ``"reliable"`` Resend attempts are sent until packets are acknowledged, and their order is preserved. Has a significant performance penalty.
  152. ``transfer_channel`` is the channel index.
  153. The first 3 can be passed in any order, but ``transfer_channel`` must always be last.
  154. The function ``multiplayer.get_remote_sender_id()`` can be used to get the unique id of an rpc sender, when used within the function called by rpc.
  155. ::
  156. func _on_some_input(): # Connected to some input.
  157. transfer_some_input.rpc_id(1) # Send the input only to the server.
  158. @rpc("any_peer", "call_local", "reliable") # Call local is required if the server is also a player.
  159. func transfer_some_input():
  160. var sender_id = multiplayer.get_remote_sender_id() # The server knows who sent the input.
  161. # Process the input and affect game logic.
  162. Channels
  163. --------
  164. Modern networking protocols support channels, which are separate connections within the connection. This allows for multiple
  165. streams of packets that do not interfere with each other.
  166. For example, game chat related messages and some of the core gameplay messages should all be sent reliably, but a gameplay
  167. message should not wait for a chat message to be acknowledged. This can be achieved by using different channels.
  168. Channels are also useful when used with the unreliable ordered transfer mode. Sending packets of variable size with this transfer mode can
  169. cause packet loss, since packets which are slower to arrive are ignored. Separating them into multiple streams of homogeneous packets
  170. by using channels allows ordered transfer with little packet loss, and without the latency penalty caused by reliable mode.
  171. The default channel with index 0 is actually three different channels - one for each transfer mode.
  172. Example lobby implementation
  173. ----------------------------
  174. This is an example lobby that can handle peers joining and leaving, notify UI scenes through signals, and start the game after all clients
  175. have loaded the game scene.
  176. ::
  177. extends Node
  178. # Autoload named Lobby
  179. # These signals can be connected to by a UI lobby scene or the game scene.
  180. signal player_connected(peer_id, player_info)
  181. signal player_disconnected(peer_id)
  182. signal server_disconnected
  183. const PORT = 7000
  184. const DEFAULT_SERVER_IP = "127.0.0.1" # IPv4 localhost
  185. const MAX_CONNECTIONS = 20
  186. # This will contain player info for every player, with the keys being each player's unique IDs.
  187. var players = {}
  188. # This is the local player info. This should be modified locally before the connection is made.
  189. # It will be passed to every other peer.
  190. # For example, the value of "name" can be set to something the player entered in a UI scene.
  191. var player_info = {"name": "Name"}
  192. var players_loaded = 0
  193. func _ready():
  194. multiplayer.peer_connected.connect(_on_player_connected)
  195. multiplayer.peer_disconnected.connect(_on_player_disconnected)
  196. multiplayer.connected_to_server.connect(_on_connected_ok)
  197. multiplayer.connection_failed.connect(_on_connected_fail)
  198. multiplayer.server_disconnected.connect(_on_server_disconnected)
  199. func join_game(address = ""):
  200. if address == "":
  201. address = DEFAULT_SERVER_IP
  202. var peer = ENetMultiplayerPeer.new()
  203. var error = peer.create_client(address, PORT)
  204. if error:
  205. return error
  206. multiplayer.multiplayer_peer = peer
  207. func create_game():
  208. var peer = ENetMultiplayerPeer.new()
  209. var error = peer.create_server(PORT, MAX_CONNECTIONS)
  210. if error:
  211. return error
  212. multiplayer.multiplayer_peer = peer
  213. players[1] = player_info
  214. player_connected.emit(1, player_info)
  215. func remove_multiplayer_peer():
  216. multiplayer.multiplayer_peer = null
  217. # When the server decides to start the game from a UI scene, do Lobby.load_game.rpc(filepath)
  218. @rpc("call_local", "reliable")
  219. func load_game(game_scene_path):
  220. get_tree().change_scene_to_file(game_scene_path)
  221. # Every peer will call this when they have loaded the game scene.
  222. @rpc("any_peer", "call_local", "reliable")
  223. func player_loaded():
  224. if multiplayer.is_server():
  225. players_loaded += 1
  226. if players_loaded == players.size():
  227. $/root/Game.start_game()
  228. players_loaded = 0
  229. # When a peer connects, send them my player info.
  230. # This allows transfer of all desired data for each player, not only the unique ID.
  231. func _on_player_connected(id):
  232. _register_player.rpc_id(id, player_info)
  233. @rpc("any_peer", "reliable")
  234. func _register_player(new_player_info):
  235. var new_player_id = multiplayer.get_remote_sender_id()
  236. players[new_player_id] = new_player_info
  237. player_connected.emit(new_player_id, new_player_info)
  238. func _on_player_disconnected(id):
  239. player_info.erase(id)
  240. player_disconnected.emit(id)
  241. func _on_connected_ok():
  242. var peer_id = multiplayer.get_unique_id()
  243. players[peer_id] = player_info
  244. player_connected.emit(peer_id, player_info)
  245. func _on_connected_fail():
  246. multiplayer.multiplayer_peer = null
  247. func _on_server_disconnected():
  248. multiplayer.multiplayer_peer = null
  249. server_disconnected.emit()
  250. The game scene's root node should be named Game. In the script attached to it:
  251. ::
  252. extends Node3D # Or Node2D.
  253. func _ready():
  254. # Preconfigure game.
  255. Lobby.player_loaded.rpc_id(1) # Tell the server that this peer has loaded.
  256. # Called only on the server.
  257. func start_game():
  258. # All peers are ready to receive RPCs in this scene.
  259. Exporting for dedicated servers
  260. -------------------------------
  261. Once you've made a multiplayer game, you may want to export it to run it on
  262. a dedicated server with no GPU available. See
  263. :ref:`doc_exporting_for_dedicated_servers` for more information.
  264. .. note::
  265. The code samples on this page aren't designed to run on a dedicated
  266. server. You'll have to modify them so the server isn't considered to be a
  267. player. You'll also have to modify the game starting mechanism so that the
  268. first player who joins can start the game.