WebSocketPeer

繼承: PacketPeer < RefCounted < Object

WebSocket 連接。

說明

這個類代表 WebSocket 連接,可以用作 WebSocket 使用者端(相容 RFC 6455),也可以用作 WebSocket 伺服器的遠端對等體。

發送 WebSocket 二進位影格請使用 PacketPeer.put_packet(),發送 WebSocket 文字影格請使用 send()(與基於文字的 API 互動時請優先選擇文字影格)。可以通過 was_string_packet() 檢查最近一個封包的框架型別。

開啟 WebSocket 使用者端的方法是:首先呼叫 connect_to_url(),然後定期調用 poll()(例如在 Node 的處理過程中)。查詢通訊端的狀態請使用 get_ready_state(),獲取掛起的封包數量請使用 PacketPeer.get_available_packet_count(),獲取掛起的封包請使用 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("資料包:", socket.get_packet())
    elif state == WebSocketPeer.STATE_CLOSING:
        # 繼續輪詢才能正確關閉。
        pass
    elif state == WebSocketPeer.STATE_CLOSED:
        var code = socket.get_close_code()
        var reason = socket.get_close_reason()
        print("WebSocket 已關閉,程式碼:%d,原因 %s。乾淨得體:%s" % [code, reason, code != -1])
        set_process(false) # 停止處理。

如果要作為 WebSocket 伺服器的對等體使用,請參考 accept_stream() 及線上教學。

屬性

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 = "") 🔗

關閉該 WebSocket 連接。code 是關閉的狀態碼(有效狀態碼的列表見 RFC 6455 第 7.4 節)。reason 是人類可讀的關閉連接原因(可以是任何小於 123 位元組的 UTF-8 字串)。如果 code 為負數,則連接會立即關閉,不通知遠程對等體。

注意:為了實作乾淨得體的關閉,你需要在達到 STATE_CLOSED 之前保持輪詢。

注意:Web 匯出可能不支援部分狀態碼。詳情請參考具體流覽器的文件。


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