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.
Checking the stable version of the documentation...
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 及在线教程。
属性
|
||
|
||
|
||
|
||
|
||
|
方法
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
🔗
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
🔗
输入缓冲区的大小,单位为字节(大致是将分配给入站数据包的最大内存量)。
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 = "") 🔗
关闭该 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.
返回收到的 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 🔗
返回该连接的就绪状态,见 State。
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。