WebSocketPeer

package
v0.0.0-...-c858641 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2025 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

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 graphics.gd/classdb/PacketPeer.Instance.PutPacket, and WebSocket text frames using Instance.Send (prefer text frames when interacting with text-based API). You can check the frame type of the last packet via Instance.WasStringPacket.

To start a WebSocket client, first call Instance.ConnectToUrl, then regularly call Instance.Poll (e.g. during graphics.gd/classdb/Node process). You can query the socket state via Instance.GetReadyState, get the number of pending packets using graphics.gd/classdb/PacketPeer.Instance.GetAvailablePacketCount, and retrieve them via graphics.gd/classdb/PacketPeer.Instance.GetPacket.

package main

import (
	"graphics.gd/classdb/Node"
	"graphics.gd/classdb/WebSocketPeer"
)

type WebSocketNode struct {
	Node.Extension[WebSocketNode]

	socket WebSocketPeer.Instance
}

func (w *WebSocketNode) Ready() {
	w.socket = WebSocketPeer.New()
	w.socket.ConnectToUrl("wss://example.com")
}

func (w *WebSocketNode) Process(_ float64) {
	w.socket.Poll()
	var state = w.socket.GetReadyState()
	switch state {
	case WebSocketPeer.StateOpen:
		for w.socket.AsPacketPeer().GetAvailablePacketCount() > 0 {
			print("Packet: ", w.socket.AsPacketPeer().GetPacket())
		}
	case WebSocketPeer.StateClosing:
		// Keep polling to achieve proper close.
	case WebSocketPeer.StateClosed:
		var code = w.socket.GetCloseCode()
		var reason = w.socket.GetCloseReason()
		print("WebSocket closed with code: %d, reason %s. Clean: %s", code, reason, code != -1)
		w.AsNode().SetProcess(false) // Stop processing.
	}
}

To use the peer as part of a WebSocket server refer to Instance.AcceptStream and the online tutorial.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Advanced

type Advanced = class

Advanced exposes a 1:1 low-level instance of the class, undocumented, for those who know what they are doing.

type Any

type Any interface {
	gd.IsClass
	AsWebSocketPeer() Instance
}

type Expanded

type Expanded [1]gdclass.WebSocketPeer

func (Expanded) Close

func (self Expanded) Close(code int, reason 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 StateClosed is reached.

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

func (Expanded) ConnectToUrl

func (self Expanded) ConnectToUrl(url string, tls_client_options TLSOptions.Instance) error

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 graphics.gd/classdb/TLSOptions.Instance.Client and graphics.gd/classdb/TLSOptions.Instance.ClientUnsafe.

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 Instance.Poll (e.g. during graphics.gd/classdb/Node process) and check the result of Instance.GetReadyState 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.

func (Expanded) Send

func (self Expanded) Send(message []byte, write_mode WriteMode) error

Sends the given 'message' using the desired 'write_mode'. When sending a string, prefer using Instance.SendText.

type Extension

type Extension[T gdclass.Interface] struct{ gdclass.Extension[T, Instance] }

Extension can be embedded in a new struct to create an extension of this class. T should be the type that is embedding this Extension

func (*Extension[T]) AsObject

func (self *Extension[T]) AsObject() [1]gd.Object

func (*Extension[T]) AsPacketPeer

func (self *Extension[T]) AsPacketPeer() PacketPeer.Instance

func (*Extension[T]) AsRefCounted

func (self *Extension[T]) AsRefCounted() [1]gd.RefCounted

func (*Extension[T]) AsWebSocketPeer

func (self *Extension[T]) AsWebSocketPeer() Instance

type ID

type ID Object.ID

ID is a typed object ID (reference) to an instance of this class, use it to store references to objects with unknown lifetimes, as an ID will not panic on use if the underlying object has been destroyed.

func (ID) Instance

func (id ID) Instance() (Instance, bool)

type Instance

type Instance [1]gdclass.WebSocketPeer

Instance of the class with convieniently typed arguments and results.

var Nil Instance

Nil is a nil/null instance of the class. Equivalent to the zero value.

func New

func New() Instance

func (Instance) AcceptStream

func (self Instance) AcceptStream(stream StreamPeer.Instance) error

Accepts a peer connection performing the HTTP handshake as a WebSocket server. The 'stream' must be a valid TCP stream retrieved via graphics.gd/classdb/TCPServer.Instance.TakeConnection, or a TLS stream accepted via graphics.gd/classdb/StreamPeerTLS.Instance.AcceptStream.

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

func (Instance) AsObject

func (self Instance) AsObject() [1]gd.Object

func (Instance) AsPacketPeer

func (self Instance) AsPacketPeer() PacketPeer.Instance

func (Instance) AsRefCounted

func (self Instance) AsRefCounted() [1]gd.RefCounted

func (Instance) AsWebSocketPeer

func (self Instance) AsWebSocketPeer() Instance

func (Instance) Close

func (self Instance) Close()

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 StateClosed is reached.

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

func (Instance) ConnectToUrl

func (self Instance) ConnectToUrl(url string) error

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 graphics.gd/classdb/TLSOptions.Instance.Client and graphics.gd/classdb/TLSOptions.Instance.ClientUnsafe.

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 Instance.Poll (e.g. during graphics.gd/classdb/Node process) and check the result of Instance.GetReadyState 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.

func (Instance) GetCloseCode

func (self Instance) GetCloseCode() int

Returns the received WebSocket close frame status code, or -1 when the connection was not cleanly closed. Only call this method when Instance.GetReadyState returns StateClosed.

func (Instance) GetCloseReason

func (self Instance) GetCloseReason() string

Returns the received WebSocket close frame status reason string. Only call this method when Instance.GetReadyState returns StateClosed.

func (Instance) GetConnectedHost

func (self Instance) GetConnectedHost() string

Returns the IP address of the connected peer.

Note: Not available in the Web export.

func (Instance) GetConnectedPort

func (self Instance) GetConnectedPort() int

Returns the remote port of the connected peer.

Note: Not available in the Web export.

func (Instance) GetCurrentOutboundBufferedAmount

func (self Instance) GetCurrentOutboundBufferedAmount() 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.

func (Instance) GetReadyState

func (self Instance) GetReadyState() State

Returns the ready state of the connection. See State.

func (Instance) GetRequestedUrl

func (self Instance) GetRequestedUrl() string

Returns the URL requested by this peer. The URL is derived from the url passed to Instance.ConnectToUrl or from the HTTP headers when acting as server (i.e. when using Instance.AcceptStream).

func (Instance) GetSelectedProtocol

func (self Instance) GetSelectedProtocol() string

Returns the selected WebSocket sub-protocol for this connection or an empty string if the sub-protocol has not been selected yet.

func (Instance) HandshakeHeaders

func (self Instance) HandshakeHeaders() []string

func (Instance) HeartbeatInterval

func (self Instance) HeartbeatInterval() Float.X

func (Instance) ID

func (self Instance) ID() ID

func (Instance) InboundBufferSize

func (self Instance) InboundBufferSize() int

func (Instance) MaxQueuedPackets

func (self Instance) MaxQueuedPackets() int

func (Instance) OutboundBufferSize

func (self Instance) OutboundBufferSize() int

func (Instance) Poll

func (self Instance) Poll()

Updates the connection state and receive incoming packets. Call this function regularly to keep it in a clean state.

func (Instance) Send

func (self Instance) Send(message []byte) error

Sends the given 'message' using the desired 'write_mode'. When sending a string, prefer using Instance.SendText.

func (Instance) SendText

func (self Instance) SendText(message string) error

Sends the given 'message' using WebSocket text mode. Prefer this method over graphics.gd/classdb/PacketPeer.Instance.PutPacket when interacting with third-party text-based API (e.g. when using graphics.gd/classdb/JSON formatted messages).

func (Instance) SetHandshakeHeaders

func (self Instance) SetHandshakeHeaders(value []string)

func (Instance) SetHeartbeatInterval

func (self Instance) SetHeartbeatInterval(value Float.X)

func (Instance) SetInboundBufferSize

func (self Instance) SetInboundBufferSize(value int)

func (Instance) SetMaxQueuedPackets

func (self Instance) SetMaxQueuedPackets(value int)

func (Instance) SetNoDelay

func (self Instance) SetNoDelay(enabled bool)

Disable Nagle's algorithm on the underlying TCP socket (default). See graphics.gd/classdb/StreamPeerTCP.Instance.SetNoDelay for more information.

Note: Not available in the Web export.

func (*Instance) SetObject

func (self *Instance) SetObject(obj [1]gd.Object) bool

func (Instance) SetOutboundBufferSize

func (self Instance) SetOutboundBufferSize(value int)

func (Instance) SetSupportedProtocols

func (self Instance) SetSupportedProtocols(value []string)

func (Instance) SupportedProtocols

func (self Instance) SupportedProtocols() []string

func (Instance) Virtual

func (self Instance) Virtual(name string) reflect.Value

func (Instance) WasStringPacket

func (self Instance) WasStringPacket() bool

Returns true if the last received packet was sent as a text payload. See WriteMode.

type State

type State int //gd:WebSocketPeer.State
const (
	// Socket has been created. The connection is not yet open.
	StateConnecting State = 0
	// The connection is open and ready to communicate.
	StateOpen State = 1
	// 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.
	StateClosing State = 2
	// The connection is closed or couldn't be opened.
	StateClosed State = 3
)

type WriteMode

type WriteMode int //gd:WebSocketPeer.WriteMode
const (
	// Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).
	WriteModeText WriteMode = 0
	// Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed).
	WriteModeBinary WriteMode = 1
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL