Class WebSocketPeer
A WebSocket connection.
- Inheritance
-
WebSocketPeer
Remarks
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 WebSocketPeer.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 WebSocketPeer.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 get_available_packet_count, and retrieve them via 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 WebSocketPeer.accept_stream and the online tutorial.
Properties
handshake_headers
The extra HTTP headers to be sent during the WebSocket handshake.
Note: Not supported in Web exports due to browsers' restrictions.
var handshake_headers : PackedStringArray = PackedStringArray()
Property Value
Remarks
- void set_handshake_headers(PackedStringArray value)
- PackedStringArray get_handshake_headers
heartbeat_interval
The interval (in seconds) at which the peer will automatically send WebSocket "ping" control frames. When set to 0
, no "ping" control frames will be sent.
Note: Has no effect in Web exports due to browser restrictions.
var heartbeat_interval : float = 0.0
Property Value
Remarks
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).
var inbound_buffer_size : int = 65535
Property Value
Remarks
max_queued_packets
The maximum amount of packets that will be allowed in the queues (both inbound and outbound).
var max_queued_packets : int = 4096
Property Value
Remarks
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).
var outbound_buffer_size : int = 65535
Property Value
Remarks
supported_protocols
The WebSocket sub-protocols allowed during the WebSocket handshake.
var supported_protocols : PackedStringArray = PackedStringArray()
Property Value
Remarks
- void set_supported_protocols(PackedStringArray value)
- PackedStringArray get_supported_protocols
Methods
accept_stream(StreamPeer)
Accepts a peer connection performing the HTTP handshake as a WebSocket server. The stream
must be a valid TCP stream retrieved via take_connection, or a TLS stream accepted via StreamPeerTLS.accept_stream.
Note: Not supported in Web exports due to browsers' restrictions.
int accept_stream(StreamPeer stream)
Parameters
stream
StreamPeer
close(int, String)
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 WebSocketPeer.STATE_CLOSED is reached.
Note: The Web export might not support all status codes. Please refer to browser-specific documentation for more details.
void close(int code, String reason)
Parameters
connect_to_url(String, TLSOptions)
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 customize the trusted certification authorities, or disable the common name verification. See TLSOptions.client and TLSOptions.client_unsafe.
Note: This method is non-blocking, and will return @GlobalScope.OK before the connection is established as long as the provided parameters are valid and the peer is not in an invalid state (e.g. already connected). Regularly call poll (e.g. during Node process) and check the result of get_ready_state to know whether the connection succeeds or fails.
Note: To avoid mixed content warnings or errors in Web, you may have to use a url
that starts with wss://
(secure) instead of ws://
. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's TLS certificate. Do not connect directly via the IP address for wss://
connections, as it won't match with the TLS certificate.
int connect_to_url(String url, TLSOptions tls_client_options)
Parameters
url
Stringtls_client_options
TLSOptions
get_close_code
Qualifiers: const
Returns the received WebSocket close frame status code, or -1
when the connection was not cleanly closed. Only call this method when get_ready_state returns WebSocketPeer.STATE_CLOSED.
int get_close_code
get_close_reason
Qualifiers: const
Returns the received WebSocket close frame status reason string. Only call this method when get_ready_state returns WebSocketPeer.STATE_CLOSED.
String get_close_reason
get_connected_host
Qualifiers: const
Returns the IP address of the connected peer.
Note: Not available in the Web export.
String get_connected_host
get_connected_port
Qualifiers: const
Returns the remote port of the connected peer.
Note: Not available in the Web export.
int get_connected_port
get_current_outbound_buffered_amount
Qualifiers: const
Returns the current amount of data in the outbound websocket buffer. Note: Web exports use WebSocket.bufferedAmount, while other platforms use an internal buffer.
int get_current_outbound_buffered_amount
get_ready_state
Qualifiers: const
Returns the ready state of the connection. See State.
int get_ready_state
get_requested_url
Qualifiers: const
Returns the URL requested by this peer. The URL is derived from the url
passed to WebSocketPeer.connect_to_url or from the HTTP headers when acting as server (i.e. when using WebSocketPeer.accept_stream).
String get_requested_url
get_selected_protocol
Qualifiers: const
Returns the selected WebSocket sub-protocol for this connection or an empty string if the sub-protocol has not been selected yet.
String get_selected_protocol
poll
Updates the connection state and receive incoming packets. Call this function regularly to keep it in a clean state.
void poll
send(PackedByteArray, int)
Sends the given message
using the desired write_mode
. When sending a String, prefer using WebSocketPeer.send_text.
int send(PackedByteArray message, int write_mode)
Parameters
message
PackedByteArraywrite_mode
int
send_text(String)
Sends the given message
using WebSocket text mode. Prefer this method over PacketPeer.put_packet when interacting with third-party text-based API (e.g. when using JSON formatted messages).
int send_text(String message)
Parameters
message
String
set_no_delay(bool)
Disable Nagle's algorithm on the underlying TCP socket (default). See StreamPeerTCP.set_no_delay for more information.
Note: Not available in the Web export.
void set_no_delay(bool enabled)
Parameters
enabled
bool
was_string_packet
Qualifiers: const
Returns true
if the last received packet was sent as a text payload. See WriteMode.
bool was_string_packet