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

max_queued_packets

2048

int

outbound_buffer_size

65535

PackedStringArray

supported_protocols

PackedStringArray()

Methods

Error

accept_stream ( StreamPeer stream )

void

close ( int code=1000, String reason="" )

Error

connect_to_url ( String url, TLSOptions tls_client_options=null )

int

get_close_code ( ) const

String

get_close_reason ( ) const

String

get_connected_host ( ) const

int

get_connected_port ( ) const

int

get_current_outbound_buffered_amount ( ) const

State

get_ready_state ( ) const

String

get_requested_url ( ) const

String

get_selected_protocol ( ) const

void

poll ( )

Error

send ( PackedByteArray message, WriteMode write_mode=1 )

Error

send_text ( String message )

void

set_no_delay ( bool enabled )

bool

was_string_packet ( ) const


Enumerations

enum WriteMode:

WriteMode WRITE_MODE_TEXT = 0

Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).

WriteMode WRITE_MODE_BINARY = 1

Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed).


enum State:

State STATE_CONNECTING = 0

Socket has been created. The connection is not yet open.

State STATE_OPEN = 1

The connection is open and ready to communicate.

State STATE_CLOSING = 2

The connection is in the process of closing. This means a close request has been sent to the remote peer but confirmation has not been received.

State STATE_CLOSED = 3

The connection is closed or couldn't be opened.


Property Descriptions

PackedStringArray handshake_headers = PackedStringArray()

The extra HTTP headers to be sent during the WebSocket handshake.

Note: Not supported in Web exports due to browsers' restrictions.


int inbound_buffer_size = 65535

  • void set_inbound_buffer_size ( int value )

  • int get_inbound_buffer_size ( )

The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the inbound packets).


int max_queued_packets = 2048

  • void set_max_queued_packets ( int value )

  • int get_max_queued_packets ( )

The maximum amount of packets that will be allowed in the queues (both inbound and outbound).


int outbound_buffer_size = 65535

  • void set_outbound_buffer_size ( int value )

  • int get_outbound_buffer_size ( )

The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the outbound packets).


PackedStringArray supported_protocols = PackedStringArray()

The WebSocket sub-protocols allowed during the WebSocket handshake.


Method Descriptions

Error accept_stream ( StreamPeer stream )

Accepts a peer connection performing the HTTP handshake as a WebSocket server. The stream must be a valid TCP stream retrieved via TCPServer.take_connection, or a TLS stream accepted via StreamPeerTLS.accept_stream.

Note: Not supported in Web exports due to browsers' restrictions.


void close ( int code=1000, String reason="" )

Closes this WebSocket connection. code is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). reason is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes). If code is negative, the connection will be closed immediately without notifying the remote peer.

Note: To achieve a clean close, you will need to keep polling until STATE_CLOSED is reached.

Note: The Web export might not support all status codes. Please refer to browser-specific documentation for more details.


Error connect_to_url ( String url, TLSOptions tls_client_options=null )

Connects to the given URL. TLS certificates will be verified against the hostname when connecting using the wss:// protocol. You can pass the optional tls_client_options parameter to cus