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.
属性
|
||
|
||
|
||
|
||
|
||
|
方法
accept_stream(stream: StreamPeer) |
|
void |
|
connect_to_url(url: String, tls_client_options: TLSOptions = null) |
|
get_close_code() const |
|
get_close_reason() const |
|
get_connected_host() const |
|
get_connected_port() const |
|
get_ready_state() const |
|
get_requested_url() const |
|
get_selected_protocol() const |
|
void |
poll() |
send(message: PackedByteArray, write_mode: WriteMode = 1) |
|
void |
set_no_delay(enabled: 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() 🔗
void set_handshake_headers(value: PackedStringArray)
PackedStringArray get_handshake_headers()
在 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 🔗
对等体自动发送 WebSocket“ping”控制帧的间隔(单位为秒)。设为 0 时不会发送“ping”控制帧。
注意:由于浏览器的限制,在 Web 导出中无效。
int inbound_buffer_size = 65535 🔗
输入缓冲区的大小,单位为字节(大致是将分配给入站数据包的最大内存量)。
int max_queued_packets = 4096 🔗
队列中允许的最大数据包数量(包括入站和出站)。
int outbound_buffer_size = 65535 🔗
输入缓冲区的大小,单位为字节(大致是将分配给出站数据包的最大内存量)。
PackedStringArray supported_protocols = PackedStringArray() 🔗
void set_supported_protocols(value: PackedStringArray)
PackedStringArray get_supported_protocols()
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) 🔗
连接到给定的 URL。使用 wss:// 协议连接时会校验 TLS 证书与主机名。传入可选的 tls_client_options 参数可以自定义信任的证书颁发机构,也可以禁用通用名校验。见 TLSOptions.client() 和 TLSOptions.client_unsafe()。
注意:该方法不会阻塞,只要提供的参数有效且对等体不处于无效状态(例如已连接)就会在建立连接前返回 @GlobalScope.OK。要检测连接成功还是失败,请定期调用 poll()(例如在 Node 的处理方法中)并检查 get_ready_state() 的结果。
注意:为了避免 Web 中的混合内容警告或错误,你可能需要使用以 wss://(安全)开头的 url 而不是 ws://。采用这种做法时,请确保使用与服务器 TLS 证书相匹配的主机域名全称。wss:// 连接请勿直接使用 IP 地址连接,因为不会与 TLS 证书匹配。
返回收到的 WebSocket 关闭帧状态码,如果连接没有干净地关闭则返回 -1。get_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 🔗
返回该连接的就绪状态。
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) 🔗
禁用底层 TCP 套接字的 Nagle 算法(默认)。详见 StreamPeerTCP.set_no_delay()。
注意:在 Web 导出中不可用。
bool was_string_packet() const 🔗
如果最后收到的数据包是作为文本有效载荷发送的,返回 true。见 WriteMode。