Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

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"