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