WebSocketPeer in Godot – Complete Guide

Welcome to the world of real-time communication in the Godot Engine! As games and applications become more interactive and connected, the need for real-time networking capabilities has never been greater. In this tutorial, we’ll dive into the WebSocketPeer class provided in Godot 4, a powerful tool for establishing WebSocket connections for both clients and servers. But what is a WebSocket connection and why is it essential to modern game development? Stick with us as we explore these questions in a clear, beginner-friendly manner, and demonstrate how you can harness the power of WebSockets in your Godot projects.

What is WebSocketPeer?

WebSocketPeer is a class in Godot 4 that represents a WebSocket connection. This versatile class not only allows you to create WebSocket clients that comply with RFC 6455 but can also act as a remote peer within a WebSocket server environment. It provides you with the methods and properties necessary to send and receive both binary and text frames, manage connection states, and handle data packets effortlessly.

What is it for?

WebSockets offer a bi-directional communication channel over a single, persistent connection, which is essential for real-time applications. In game development, this means you can create multiplayer games, chat systems, or any feature that requires live updates without the need to constantly poll the server or reload the page.

Why Should I Learn It?

For any game developer, understanding the flow of real-time data is crucial to designing engaging and dynamic experiences. By learning about WebSocketPeer in Godot 4, you’ll be able to create more responsive and interactive games. As the gaming industry continues to trend towards multiplayer and collaborative experiences, having a grasp of WebSocket technology positions you at the forefront of game development innovations.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Establishing a WebSocket Client Connection

To get started with using WebSocketPeer in Godot, the first step is to establish a client connection. The following code demonstrates how to create a WebSocket client that connects to a server:

var ws = WebSocketClient.new()

func _ready():
    var url = "ws://echo.websocket.org"
    ws.connect("connection_established", self, "_on_connection_established")
    ws.connect("connection_error", self, "_on_connection_error")
    ws.connect_to_url(url)
    
func _on_connection_established(protocol):
    print("Connection established with protocol: " + protocol)

func _on_connection_error():
    print("Connection failed.")

Here we use `WebSocketClient.new()` to create a new client instance. We then connect two important signals, `connection_established` and `connection_error`, to inform us when the connection is successfully established or if an error occurs.

Sending and Receiving Data

Once the connection is established, you can send data using the `send_text` or `send_binary` methods.

func send_message(message):
    if ws.get_connection_status() == WebSocketClient.CONNECTION_CONNECTED:
        ws.send_text(message)

func _process(delta):
    ws.poll()
    while ws.get_peer(1).get_available_packet_count() > 0:
        var message = ws.get_peer(1).get_packet().get_string_from_utf8()
        print("Received message: " + message)

This sends a text message to the server. We first check if the connection is established. The `poll` method updates the WebSocket state, and we use `get_peer(1)` to retrieve data from the server. The received message is then decoded from UTF-8 and printed.

Handling Disconnections

Good networking practice demands handling disconnections gracefully. This can be accomplished by tracking the `connection_closed` signal:

ws.connect("connection_closed", self, "_on_connection_closed")

func _on_connection_closed(was_clean_close):
    print("Connection closed" + (". It was clean" if was_clean_close else ", with an error."))

The `connection_closed` signal provides an argument to indicate whether the disconnection was clean or resulted from an error.

Setting up a WebSocket Server

On the server side, setting up a WebSocket server in Godot is equally straightforward. Here’s how to create and start a server:

var wss = WebSocketServer.new()

func start_server(port):
    wss.listen(port, [], true)
    wss.connect("client_connected", self, "_on_client_connected")
    wss.connect("client_disconnected", self, "_on_client_disconnected")

func _on_client_connected(id, protocol):
    print("Client connected with id: " + str(id) + " and protocol: " + protocol)

func _on_client_disconnected(id, was_clean_close):
    print("Client disconnected with id: " + str(id) + (". It was clean" if was_clean_close else ", with an error."))

This snippet sets up a new `WebSocketServer` and starts listening to a given port. Similarly, as with the client, we connect signals to react to clients connecting or disconnecting.

In these examples, we’ve covered the primary steps in establishing WebSocket connections, sending and receiving data, and handling connection lifecycle events in Godot. In the next part of the tutorial, we will build upon these basics to create a simple interactive experience using WebSocketPeer.Creating a Simple Chat Application
As a practical application of WebSocketPeer, we’ll develop a rudimentary chat application. We will enable users to connect to a WebSocket server and exchange messages in real-time.

Starting with the client, let’s build upon the previous example to enable sending chat messages via the UI.

“`html