Work in progress
The content of this page was not yet updated for Godot
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.
HTML5 and WebSocket¶
The WebSocket protocol was standardized in 2011 with the original goal of allowing browsers to create stable and bidirectional connections with a server. Before that, browsers used to only support HTTPRequests, which is not well-suited for bidirectional communication.
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 WebRTC for those use cases).
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.
Godot supports WebSocket in both native and HTML5 exports.
Using WebSocket in Godot¶
When exporting to Android, make sure to enable the
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 client example¶
This example will show you how to create a WebSocket connection to a remote server, and how to send and receive data.
extends Node # The URL we will connect to export var websocket_url = "wss://libwebsockets.org" # Our WebSocketClient instance var _client = WebSocketClient.new() func _ready(): # Connect base signals to get notified of connection open, close, and errors. _client.connection_closed.connect(_closed) _client.connection_error.connect(_closed) _client.connection_established.connect(_connected) # This signal is emitted when not using the Multiplayer API every time # a full packet is received. # Alternatively, you could check get_peer(1).get_available_packets() in a loop. _client.data_received.connect(_on_data) # Initiate connection to the given URL. var err = _client.connect_to_url(websocket_url, ["lws-mirror-protocol"]) if err != OK: print("Unable to connect") set_process(false) func _closed(was_clean = false): # was_clean will tell you if the disconnection was correctly notified # by the remote peer be