WebSocket

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 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 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

WebSocket is implemented in Godot via three main classes WebSocketClient, WebSocketServer, and WebSocketPeer. The WebSocket implementation is compatible with the High Level Multiplayer. See section on high-level multiplayer for more details.

Warning

When exporting to Android, make sure to enable the [code]INTERNET[/code] 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.

  1. extends Node
  2. # The URL we will connect to
  3. export var websocket_url = "ws://echo.websocket.org"
  4. # Our WebSocketClient instance
  5. var _client = WebSocketClient.new()
  6. func _ready():
  7. # Connect base signals to get notified of connection open, close, and errors.
  8. _client.connect("connection_closed", self, "_closed")
  9. _client.connect("connection_error", self, "_closed")
  10. _client.connect("connection_established", self, "_connected")
  11. # This signal is emitted when not using the Multiplayer API every time
  12. # a full packet is received.
  13. # Alternatively, you could check get_peer(1).get_available_packets() in a loop.
  14. _client.connect("data_received", self, "_on_data")
  15. # Initiate connection to the given URL.
  16. var err = _client.connect_to_url(websocket_url)
  17. if err != OK:
  18. print("Unable to connect")
  19. set_process(false)
  20. func _closed(was_clean = false):
  21. # was_clean will tell you if the disconnection was correctly notified
  22. # by the remote peer before closing the socket.
  23. print("Closed, clean: ", was_clean)
  24. set_process(false)
  25. func _connected(proto = ""):
  26. # This is called on connection, "proto" will be the selected WebSocket
  27. # sub-protocol (which is optional)
  28. print("Connected with protocol: ", proto)
  29. # You MUST always use get_peer(1).put_packet to send data to server,
  30. # and not put_packet directly when not using the MultiplayerAPI.
  31. _client.get_peer(1).put_packet("Test packet".to_utf8())
  32. func _on_data():
  33. # Print the received packet, you MUST always use get_peer(1).get_packet
  34. # to receive data from server, and not get_packet directly when not
  35. # using the MultiplayerAPI.
  36. print("Got data from server: ", _client.get_peer(1).get_packet().get_string_from_utf8())
  37. func _process(delta):
  38. # Call this in _process or _physics_process. Data transfer, and signals
  39. # emission will only happen when calling this function.
  40. _client.poll()

This will print:

  1. Connected with protocol:
  2. Got data from server: Test packet

Minimal server example

This example will show you how to create a WebSocket server that listens for remote connections, and how to send and receive data.

  1. extends Node
  2. # The port we will listen to
  3. const PORT = 9080
  4. # Our WebSocketServer instance
  5. var _server = WebSocketServer.new()
  6. func _ready():
  7. # Connect base signals to get notified of new client connections,
  8. # disconnections, and disconnect requests.
  9. _server.connect("client_connected", self, "_connected")
  10. _server.connect("client_disconnected", self, "_disconnected")
  11. _server.connect("client_close_request", self, "_close_request")
  12. # This signal is emitted when not using the Multiplayer API every time a
  13. # full packet is received.
  14. # Alternatively, you could check get_peer(PEER_ID).get_available_packets()
  15. # in a loop for each connected peer.
  16. _server.connect("data_received", self, "_on_data")
  17. # Start listening on the given port.
  18. var err = _server.listen(PORT)
  19. if err != OK:
  20. print("Unable to start server")
  21. set_process(false)
  22. func _connected(id, proto):
  23. # This is called when a new peer connects, "id" will be the assigned peer id,
  24. # "proto" will be the selected WebSocket sub-protocol (which is optional)
  25. print("Client %d connected with protocol: %s" % [id, proto])
  26. func _close_request(id, code, reason):
  27. # This is called when a client notifies that it wishes to close the connection,
  28. # providing a reason string and close code.
  29. print("Client %d disconnecting with code: %d, reason: %s" % [id, code, reason])
  30. func _disconnected(id, was_clean = false):
  31. # This is called when a client disconnects, "id" will be the one of the
  32. # disconnecting client, "was_clean" will tell you if the disconnection
  33. # was correctly notified by the remote peer before closing the socket.
  34. print("Client %d disconnected, clean: %s" % [id, str(was_clean)])
  35. func _on_data(id):
  36. # Print the received packet, you MUST always use get_peer(id).get_packet to receive data,
  37. # and not get_packet directly when not using the MultiplayerAPI.
  38. var pkt = _server.get_peer(id).get_packet()
  39. print("Got data from client %d: %s ... echoing" % [id, pkt.get_string_from_utf8()])
  40. _server.get_peer(id).put_packet(pkt)
  41. func _process(delta):
  42. # Call this in _process or _physics_process.
  43. # Data transfer, and signals emission will only happen when calling this function.
  44. _server.poll()

This will print (when a client connects) something similar to this:

  1. Client 1348090059 connected with protocol: selected-protocol
  2. Got data from client 1348090059: Test packet ... echoing

Advanced chat demo

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 under networking/websocket_chat and networking/websocket_multiplayer.