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

繼承: PacketPeer < RefCounted < Object

WebSocket 連接。

說明

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.

屬性

PackedStringArray

handshake_headers

PackedStringArray()

float

heartbeat_interval

0.0

int

inbound_buffer_size

65535

int

max_queued_packets

4096

int

outbound_buffer_size

65535

PackedStringArray

supported_protocols

PackedStringArray()

方法

Error

accept_stream(stream: StreamPeer)

void

close(code: int = 1000, reason: String = "")

Error

connect_to_url(url: String, tls_client_options: TLSOptions = 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(message: PackedByteArray, write_mode: WriteMode = 1)

Error

send_text(message: String)

void

set_no_delay(enabled: bool)

bool

was_string_packet() const


列舉

enum WriteMode: 🔗

WriteMode WRITE_MODE_TEXT = 0

指定 WebSockets 消息應作為文字有效載荷傳輸(只允許有效的 UTF-8)。

WriteMode WRITE_MODE_BINARY = 1

指定 WebSockets 消息應以二進位有效載荷的形式傳輸(允許任何位元組組合)。


enum State: 🔗

State STATE_CONNECTING = 0

已建立通訊端。連接尚未打開。

State STATE_OPEN = 1

連接已打開,通訊就緒。

State STATE_CLOSING = 2

連接正在關閉過程中。這意味著已經向遠端對等體發送了關閉請求,但還沒有收到確認。

State STATE_CLOSED = 3

連接已關閉或無法打開。


屬性說明

PackedStringArray handshake_headers = PackedStringArray() 🔗

在 WebSocket 握手過程中要發送的額外 HTTP 標頭。

注意:由於流覽器的限制,在 Web 匯出中不支援。

Note: The returned array is copied and any changes to it will not update the original property value. See PackedStringArray for more details.


float heartbeat_interval = 0.0 🔗

  • void set_heartbeat_interval(value: float)

  • float get_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.


int inbound_buffer_size = 65535 🔗

  • void set_inbound_buffer_size(value: int)

  • int get_inbound_buffer_size()

輸入緩衝區的大小,單位為位元組(大致是將分配給入站封包的最大記憶體量)。


int max_queued_packets = 4096 🔗

  • void set_max_queued_packets(value: int)

  • int get_max_queued_packets()

佇列中允許的最大封包數量(包括入站和出站)。


int outbound_buffer_size = 65535 🔗

  • void set_outbound_buffer_size(value: int)

  • int get_outbound_buffer_size()

輸入緩衝區的大小,單位為位元組(大致是將分配給出站封包的最大記憶體量)。


PackedStringArray supported_protocols = PackedStringArray() 🔗

WebSocket 握手期間允許的 WebSocket 子協議。

Note: The returned array is copied and any changes to it will not update the original property value. See PackedStringArray for more details.


方法說明

Error accept_stream(stream: StreamPeer) 🔗

以 WebSocket 伺服器的名義,接受正在執行 HTTP 握手的對等體連接。stream 必須是從 TCPServer.take_connection() 獲取的有效 TCP 流,或者是從 StreamPeerTLS.accept_stream() 接受的 TLS 流。

注意:由於流覽器的限制,Web 匯出中不支援此方法。


void close(code: int = 1000, 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). If code is negative, the connection will be closed immediately without notifying the remote peer.

reason is the human-readable reason for closing the connection. It can be any UTF-8 string that's smaller than 123 bytes.

Note: To achieve a clean closure, 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.


Error connect_to_url(url: String, tls_client_options: TLSOptions = null) 🔗

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 get_close_code() const 🔗

返回收到的 WebSocket 關閉影格狀態碼,如果連接沒有乾淨地關閉則返回 -1get_ready_state() 返回 STATE_CLOSED 才能呼叫這個方法。


String get_close_reason() const 🔗

返回收到的 WebSocket 關閉影格狀態原因字串。get_ready_state() 返回 STATE_CLOSED 才能呼叫這個方法。


String get_connected_host() const 🔗

返回已連接對等體的 IP 位址。

注意:在 Web 匯出中不可用。


int get_connected_port() const 🔗

返回已連接對等體的遠端埠。

注意:在 Web 匯出中不可用。


int get_current_outbound_buffered_amount() const 🔗

返回 websocket 輸出緩衝區中的目前資料量。注意:Web 匯出使用 WebSocket.bufferedAmount,而其他平臺使用內部緩衝區。


State get_ready_state() const 🔗

Returns the ready state of the connection.


String get_requested_url() const 🔗

返回該對等體請求的 URL。該 URL 由傳給 connect_to_url()url 得出,作為伺服器時則從 HTTP 標頭獲取(即使用 accept_stream() 時)。


String get_selected_protocol() const 🔗

返回這個連接所選用的 WebSocket 子協議,如果未選擇子協定則返回空字串。


void poll() 🔗

更新連接狀態並接收傳入的封包。請定期呼叫此函式,保持其清潔狀態。


Error send(message: PackedByteArray, write_mode: WriteMode = 1) 🔗

使用期望的 write_mode 發送給定的 message。發送 String 時,請優先使用 send_text()


Error send_text(message: String) 🔗

使用 WebSocket 文字模式發送給定的 message。與協力廠商文字 API 互動時請優先使用這個方法而不是 PacketPeer.put_packet()(例如使用 JSON 格式的消息時)。


void set_no_delay(enabled: 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.


bool was_string_packet() const 🔗

如果最後收到的封包是作為文字有效載荷發送的,返回 true。見 WriteMode