Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

WebSocketPeer

Inherits: PacketPeer < RefCounted < Object

A WebSocket connection.

Description

This class represents WebSocket connection, and can be used as a WebSocket client (RFC 6455-compliant) or as a remote peer of a WebSocket server.

You can send WebSocket binary frames using PacketPeer.put_packet, and WebSocket text frames using send (prefer text frames when interacting with text-based API). You can check the frame type of the last packet via was_string_packet.

To start a WebSocket client, first call connect_to_url, then regularly call poll (e.g. during Node process). You can query the socket state via get_ready_state, get the number of pending packets using PacketPeer.get_available_packet_count, and retrieve them via PacketPeer.get_packet.

extends Node

var socket = WebSocketPeer.new()

func _ready():
    socket.connect_to_url("wss://example.com")

func _process(delta):
    socket.poll()
    var state = socket.get_ready_state()
    if state == WebSocketPeer.STATE_OPEN:
        while socket.get_available_packet_count():
            print("Packet: ", socket.get_packet())
    elif state == WebSocketPeer.STATE_CLOSING:
        # Keep polling to achieve proper close.
        pass
    elif state == WebSocketPeer.STATE_CLOSED:
        var code = socket.get_close_code()
        var reason = socket.get_close_reason()
        print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1])
        set_process(false) # Stop processing.

To use the peer as part of a WebSocket server refer to accept_stream and the online tutorial.

Properties

PackedStringArray

handshake_headers

PackedStringArray()

int

inbound_buffer_size

65535

int