Inheritance #
- AudioServer
- CameraServer
- ClassDB
- DisplayServer
- EditorFileSystemDirectory
- EditorInterface
- EditorPaths
- EditorSelection
- EditorUndoRedoManager
- EditorVCSInterface
- Engine
- EngineDebugger
- FramebufferCacheRD
- GDExtensionManager
- Geometry2D
- Geometry3D
- IP
- Input
- InputMap
- JNISingleton
- JSONRPC
- JavaClassWrapper
- JavaScriptBridge
- MainLoop (1)
- Marshalls
- MovieWriter
- NativeMenu
- NavigationMeshGenerator
- NavigationServer2D
- NavigationServer3D
- Node (21)
- OS
- OpenXRExtensionWrapperExtension
- OpenXRInteractionProfileMetadata
- Performance
- PhysicsDirectBodyState2D (1)
- PhysicsDirectBodyState3D (1)
- PhysicsDirectSpaceState2D (1)
- PhysicsDirectSpaceState3D (1)
- PhysicsServer2D (1)
- PhysicsServer2DManager
- PhysicsServer3D (1)
- PhysicsServer3DManager
- PhysicsServer3DRendering
ServerHandler
- ProjectSettings
- RefCounted (121)
- RenderData (2)
- RenderSceneData (2)
- RenderingDevice
- RenderingServer
- ResourceLoader
- ResourceSaver
- ResourceUID
- ScriptLanguage (1)
- ShaderIncludeDB
- TextServerManager
- ThemeDB
- TileData
- Time
- TranslationServer
- TreeItem
- UndoRedo
- UniformSetCacheRD
- WorkerThreadPool
- XRServer
- XRVRS
- AESContext
- AStar2D
- AStar3D
- AStarGrid2D
- AudioEffectInstance (1)
- AudioSample
- AudioSamplePlayback
- AudioStreamPlayback (5)
- CameraFeed
- CharFXTransform
- ConfigFile
- Crypto
- DTLSServer
- DirAccess
- ENetConnection
- EditorContextMenuPlugin
- EditorDebuggerPlugin
- EditorDebuggerSession
- EditorExportPlatform (6)
- EditorExportPlugin
- EditorExportPreset
- EditorFeatureProfile
- EditorFileSystemImportFormatSupportQuery
- EditorInspectorPlugin
- EditorResourceConversionPlugin
- EditorResourcePreviewGenerator
- EditorResourceTooltipPlugin
- EditorSceneFormatImporter (4)
- EditorScenePostImport
- EditorScenePostImportPlugin
- EditorScript
- EditorTranslationParserPlugin
- EncodedObjectAsID
- EngineProfiler
- Expression
- FileAccess
- GLTFObjectModelProperty
- HMACContext
- HTTPClient
- HashingContext
- ImageFormatLoader (1)
- JavaClass
- JavaObject
- JavaScriptObject
- KinematicCollision2D
- KinematicCollision3D
- Lightmapper (1)
- MeshConvexDecompositionSettings
- MeshDataTool
- MultiplayerAPI (2)
- Mutex
- NavigationPathQueryParameters2D
- NavigationPathQueryParameters3D
- NavigationPathQueryResult2D
- NavigationPathQueryResult3D
- Node3DGizmo (1)
- OggPacketSequencePlayback
- OpenXRAPIExtension
- PCKPacker
- PackedDataContainerRef
- PacketPeer (8)
- PhysicsPointQueryParameters2D
- PhysicsPointQueryParameters3D
- PhysicsRayQueryParameters2D
- PhysicsRayQueryParameters3D
- PhysicsShapeQueryParameters2D
- PhysicsShapeQueryParameters3D
- PhysicsTestMotionParameters2D
- PhysicsTestMotionParameters3D
- PhysicsTestMotionResult2D
- PhysicsTestMotionResult3D
- RDAttachmentFormat
- RDFramebufferPass
- RDPipelineColorBlendState
- RDPipelineColorBlendStateAttachment
- RDPipelineDepthStencilState
- RDPipelineMultisampleState
- RDPipelineRasterizationState
- RDPipelineSpecializationConstant
- RDSamplerState
- RDShaderSource
- RDTextureFormat
- RDTextureView
- RDUniform
- RDVertexAttribute
- RandomNumberGenerator
- RegEx
- RegExMatch
- RenderSceneBuffers (2)
- RenderSceneBuffersConfiguration
- Resource (103)
- ResourceFormatLoader
- ResourceFormatSaver
- ResourceImporter (16)
- SceneState
- SceneTreeTimer
- Semaphore
- SkinReference
- StreamPeer (5)
- SurfaceTool
- TCPServer
- TLSOptions
- TextLine
- TextParagraph
- TextServer (1)
- Thread
- TranslationDomain
- TriangleMesh
- Tween
- Tweener (5)
- UDPServer
- UPNP
- UPNPDevice
- WeakRef
- WebRTCPeerConnection (1)
- XMLParser
- XRInterface (4)
- XRPose
- XRTracker (2)
- ZIPPacker
- ZIPReader
- ENetPacketPeer
- MultiplayerPeer (5)
- PacketPeerDTLS
- PacketPeerExtension
- PacketPeerStream
- PacketPeerUDP
- WebRTCDataChannel (1)
- WebSocketPeer
Table of contents
-
var handshake_headers: PackedStringArray = PackedStringArray() -
var heartbeat_interval: float = 0.0 -
var inbound_buffer_size: int = 65535 -
var max_queued_packets: int = 4096 -
var outbound_buffer_size: int = 65535 -
var supported_protocols: PackedStringArray = PackedStringArray() -
func accept_stream(stream: StreamPeer) -> intError -
func close(reason: String = "") -> void -
func connect_to_url(tls_client_options: TLSOptions = null) -> intError -
const func get_close_code() -> int -
const func get_close_reason() -> String -
const func get_connected_host() -> String -
const func get_connected_port() -> int -
const func get_current_outbound_buffered_amount() -> int -
const func get_ready_state() -> intWebSocketPeer.State -
const func get_requested_url() -> String -
const func get_selected_protocol() -> String -
func poll() -> void -
func send(write_mode: int = 1 enumWebSocketPeer.WriteMode) -> intError -
func send_text(message: String) -> intError -
func set_no_delay(enabled: bool) -> void -
const func was_string_packet() -> bool -
const WRITE_MODE_TEXT = 0 enum WriteMode -
const WRITE_MODE_BINARY = 1 enum WriteMode -
const STATE_CONNECTING = 0 enum State -
const STATE_OPEN = 1 enum State -
const STATE_CLOSING = 2 enum State -
const STATE_CLOSED = 3 enum State -
enum WriteMode -
enum State
WebSocketPeer #
is_refcounted, is_instantiable, core, not_builtin_classes
A WebSocket connection.
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.
Members #
var handshake_headers: PackedStringArray = PackedStringArray()#
The extra HTTP headers to be sent during the WebSocket handshake.
Note: Not supported in Web exports due to browsers' restrictions.
var heartbeat_interval: float = 0.0#
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 inbound_buffer_size: int = 65535#
The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the inbound packets).
var max_queued_packets: int = 4096#
The maximum amount of packets that will be allowed in the queues (both inbound and outbound).
var outbound_buffer_size: int = 65535#
The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the outbound packets).
var supported_protocols: PackedStringArray = PackedStringArray()#
The WebSocket sub-protocols allowed during the WebSocket handshake.
Methods #
func accept_stream(stream: StreamPeer) -> intError#
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.
func close(reason: String = "") -> void#
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.
func connect_to_url(tls_client_options: TLSOptions = null) -> intError#
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 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.
const func get_close_code() -> int#
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 STATE_CLOSED.
const func get_close_reason() -> String#
Returns the received WebSocket close frame status reason string. Only call this method when get_ready_state returns STATE_CLOSED.
const func get_connected_host() -> String#
Returns the IP address of the connected peer.
Note: Not available in the Web export.
const func get_connected_port() -> int#
Returns the remote port of the connected peer.
Note: Not available in the Web export.
const func get_current_outbound_buffered_amount() -> int#
Returns the current amount of data in the outbound websocket buffer. Note: Web exports use WebSocket.bufferedAmount, while other platforms use an internal buffer.
const func get_ready_state() -> intWebSocketPeer.State#
Returns the ready state of the connection. See State.
const func get_requested_url() -> String#
Returns the URL requested by this peer. The URL is derived from the url passed to connect_to_url or from the HTTP headers when acting as server (i.e. when using accept_stream).
const func get_selected_protocol() -> String#
Returns the selected WebSocket sub-protocol for this connection or an empty string if the sub-protocol has not been selected yet.
func poll() -> void#
Updates the connection state and receive incoming packets. Call this function regularly to keep it in a clean state.
func send(write_mode: int = 1 enumWebSocketPeer.WriteMode) -> intError#
Sends the given message using the desired write_mode. When sending a String, prefer using send_text.
func send_text(message: String) -> intError#
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).
func set_no_delay(enabled: bool) -> void#
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.
const func was_string_packet() -> bool#
Returns true if the last received packet was sent as a text payload. See WriteMode.
Annotations #
Constants #
const WRITE_MODE_TEXT = 0 enum WriteMode#
Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).
const WRITE_MODE_BINARY = 1 enum WriteMode#
Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed).
const STATE_CONNECTING = 0 enum State#
Socket has been created. The connection is not yet open.
const STATE_OPEN = 1 enum State#
The connection is open and ready to communicate.
const STATE_CLOSING = 2 enum State#
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.
const STATE_CLOSED = 3 enum State#
The connection is closed or couldn't be opened.
Constructors #
Enums #
WriteMode#
enum WriteMode {
WRITE_MODE_TEXT = 0,
WRITE_MODE_BINARY = 1,
}State#
enum State {
STATE_CONNECTING = 0,
STATE_OPEN = 1,
STATE_CLOSING = 2,
STATE_CLOSED = 3,
}