Work in progress

The content of this page was not yet updated for Godot 4.3 and may be outdated. If you know how to improve this page or you can confirm that it’s up to date, feel free to open a pull request.

WebRTC

HTML5, WebSocket, WebRTC

One of Godot’s great features is its ability to export to the HTML5/WebAssembly platform, allowing your game to run directly in the browser when a user visit your webpage.

This is a great opportunity for both demos and full games, but used to come with some limitations. In the area of networking, browsers used to support only HTTPRequests until recently, when first WebSocket and then WebRTC were proposed as standards.

WebSocket

When the WebSocket protocol was standardized in December 2011, it allowed browsers to create stable and bidirectional connections to a WebSocket server. The protocol is a very powerful tool to send push notifications to browsers, and has been used to implement chats, turn-based games, etc.

WebSockets, though, still use 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.

WebRTC

For this reason, since 2010, Google started working on a new technology called WebRTC, which later on, in 2017, became a W3C candidate recommendation. WebRTC is a much more complex set of specifications, and relies on many other technologies behind the scenes (ICE, DTLS, SDP) to provide fast, real-time, and secure communication between two peers.

The idea is to find the fastest route between the two peers and establish whenever possible a direct communication (i.e. try to avoid a relaying server).

However, this comes at a price, which is that some media information must be exchanged between the two peers before the communication can start (in the form of Session Description Protocol - SDP strings). This usually takes the form of a so-called WebRTC Signaling Server.

../../_images/webrtc_signaling.png

Peers connect to a signaling server (for example a WebSocket server) and send their media information. The server then relays this information to other peers, allowing them to establish the desired direct communication. Once this step is done, peers can disconnect from the signaling server and keep the direct Peer-to-Peer (P2P) connection open.

Using WebRTC in Godot

WebRTC is implemented in Godot via two main classes WebRTCPeerConnection and WebRTCDataChannel, plus the multiplayer API implementation WebRTCMultiplayerPeer. See section on high-level multiplayer for more details.

Note

These classes are available automatically in HTML5, but require an external GDExtension plugin on native (non-HTML5) platforms. Check out the webrtc-native plugin repository for instructions and to get the latest release.

Warning

When exporting to Android, make sure to enable the INTERNET permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android.

Minimal connection example

This example will show you how to create a WebRTC connection between two peers in the same application. This is not very useful in real life, but will give you a good overview of how a WebRTC connection is set up.

  1. extends Node
  2. # Create the two peers
  3. var p1 = WebRTCPeerConnection.new()
  4. var p2 = WebRTCPeerConnection.new()
  5. # And a negotiated channel for each each peer
  6. var ch1 = p1.create_data_channel("chat", {"id": 1, "negotiated": true})
  7. var ch2 = p2.create_data_channel("chat", {"id": 1, "negotiated": true})
  8. func _ready():
  9. # Connect P1 session created to itself to set local description.
  10. p1.session_description_created.connect(p1.set_local_description)
  11. # Connect P1 session and ICE created to p2 set remote description and candidates.
  12. p1.session_description_created.connect(p2.set_remote_description)
  13. p1.ice_candidate_created.connect(p2.add_ice_candidate)
  14. # Same for P2
  15. p2.session_description_created.connect(p2.set_local_description)
  16. p2.session_description_created.connect(p1.set_remote_description)
  17. p2.ice_candidate_created.connect(p1.add_ice_candidate)
  18. # Let P1 create the offer
  19. p1.create_offer()
  20. # Wait a second and send message from P1.
  21. await get_tree().create_timer(1).timeout
  22. ch1.put_packet("Hi from P1".to_utf8_buffer())
  23. # Wait a second and send message from P2.
  24. await get_tree().create_timer(1).timeout
  25. ch2.put_packet("Hi from P2".to_utf8_buffer())
  26. func _process(_delta):
  27. # Poll connections
  28. p1.poll()
  29. p2.poll()
  30. # Check for messages
  31. if ch1.get_ready_state() == ch1.STATE_OPEN and ch1.get_available_packet_count() > 0:
  32. print("P1 received: ", ch1.get_packet().get_string_from_utf8())
  33. if ch2.get_ready_state() == ch2.STATE_OPEN and ch2.get_available_packet_count() > 0:
  34. print("P2 received: ", ch2.get_packet().get_string_from_utf8())

This will print:

  1. P1 received: Hi from P1
  2. P2 received: Hi from P2

Local signaling example

This example expands on the previous one, separating the peers in two different scenes, and using a singleton as a signaling server.

  1. extends Node
  2. # An example p2p chat client.
  3. var peer = WebRTCPeerConnection.new()
  4. # Create negotiated data channel.
  5. var channel = peer.create_data_channel("chat", {"negotiated": true, "id": 1})
  6. func _ready():
  7. # Connect all functions.
  8. peer.ice_candidate_created.connect(self._on_ice_candidate)
  9. peer.session_description_created.connect(self._on_session)
  10. # Register to the local signaling server (see below for the implementation).
  11. Signaling.register(String(get_path()))
  12. func _on_ice_candidate(mid, index, sdp):
  13. # Send the ICE candidate to the other peer via signaling server.
  14. Signaling.send_candidate(String(get_path()), mid, index, sdp)
  15. func _on_session(type, sdp):
  16. # Send the session to other peer via signaling server.
  17. Signaling.send_session(String(get_path()), type, sdp)
  18. # Set generated description as local.
  19. peer.set_local_description(type, sdp)
  20. func _process(delta):
  21. # Always poll the connection frequently.
  22. peer.poll()
  23. if channel.get_ready_state() == WebRTCDataChannel.STATE_OPEN:
  24. while channel.get_available_packet_count() > 0:
  25. print(String(get_path()), " received: ", channel.get_packet().get_string_from_utf8())
  26. func send_message(message):
  27. channel.put_packet(message.to_utf8_buffer())

And now for the local signaling server:

Note

This local signaling server is supposed to be used as a singleton to connect two peers in the same scene.

  1. # A local signaling server. Add this to autoloads with name "Signaling" (/root/Signaling)
  2. extends Node
  3. # We will store the two peers here
  4. var peers = []
  5. func register(path):
  6. assert(peers.size() < 2)
  7. peers.append(path)
  8. if peers.size() == 2:
  9. get_node(peers[0]).peer.create_offer()
  10. func _find_other(path):
  11. # Find the other registered peer.
  12. for p in peers:
  13. if p != path:
  14. return p
  15. return ""
  16. func send_session(path, type, sdp):
  17. var other = _find_other(path)
  18. assert(other != "")
  19. get_node(other).peer.set_remote_description(type, sdp)
  20. func send_candidate(path, mid, index, sdp):
  21. var other = _find_other(path)
  22. assert(other != "")
  23. get_node(other).peer.add_ice_candidate(mid, index, sdp)

Then you can use it like this:

  1. # Main scene (main.gd)
  2. extends Node
  3. const Chat = preload("res://chat.gd")
  4. func _ready():
  5. var p1 = Chat.new()
  6. var p2 = Chat.new()
  7. add_child(p1)
  8. add_child(p2)
  9. # Wait a second and send message from P1
  10. await get_tree().create_timer(1).timeout
  11. p1.send_message("Hi from %s" % String(p1.get_path()))
  12. # Wait a second and send message from P2
  13. await get_tree().create_timer(1).timeout
  14. p2.send_message("Hi from %s" % String(p2.get_path()))

This will print something similar to this:

  1. /root/main/@@3 received: Hi from /root/main/@@2
  2. /root/main/@@2 received: Hi from /root/main/@@3

Remote signaling with WebSocket

A more advanced demo using WebSocket for signaling peers and WebRTCMultiplayerPeer is available in the godot demo projects under networking/webrtc_signaling.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next