类: WebSocket 继承自 `EventTarget`
类: WebSocket 继承自 EventTarget
🌐 Class: WebSocket extends EventTarget
使用 Chromium 的原生网络库从主进程创建 WebSocket 连接
进程:主进程
🌐 Process: Main
net.WebSocket 是 WHATWG WebSocket 接口的直接替代品,它通过 Chromium 的网络栈而不是 Node.js 来路由连接。当你想要在主进程中使用 WebSocket 连接时,可以使用它,它可以:
- 使用系统或会话代理配置(PAC、WPAD)。
- 根据平台信任库和会话的证书验证策略验证 TLS 证书。
- 支持会话级别的配置(自定义证书、主机解析规则等)。
- 发送会话的 Cookie(当
useSessionCookies启用时)。
这个类实现了标准 WebSocket 接口(一个 EventTarget),所以针对浏览器或 Node.js 全局 WebSocket 编写的代码可以直接使用,无需修改:
🌐 The class implements the standard WebSocket interface
(an EventTarget), so
code written against the browser or Node.js global WebSocket works without
changes:
const { app, net } = require('electron')
app.whenReady().then(() => {
const ws = new net.WebSocket('wss://echo.websocket.events')
ws.onopen = () => ws.send('hello')
ws.onmessage = (event) => {
console.log('received', event.data)
ws.close()
}
})
net.WebSocket 只能在应用发出 ready 事件之后使用。
new WebSocket(url[, protocols])
urlstring - 要连接的 URL。协议必须是ws:或wss:(http:和https:也可以使用,但会被重写为它们的 WebSocket 等价形式,就像在浏览器中一样)。protocolsstring | string[] | WebSocketOptions(optional)- 一个或多个 WebSocket 子协议,或者一个 Electron 特定的选项对象。
将一个选项对象作为第二个参数传入是 Electron 的扩展;两参数形式 new net.WebSocket(url, protocols) 与 WHATWG 构造函数 完全兼容。
🌐 Passing an options object as the second argument is an Electron extension; the
two-argument form new net.WebSocket(url, protocols) is fully compatible with
the WHATWG constructor.
静态属性
🌐 Static Properties
WebSocket.CONNECTING 只读
🌐 WebSocket.CONNECTING Readonly
一个 Integer 常量等于 0,在开启握手过程时的 readyState 值。
🌐 An Integer constant equal to 0, the readyState value while the opening
handshake is in progress.
WebSocket.OPEN 只读
🌐 WebSocket.OPEN Readonly
Integer 常量等于 1,连接建立后 readyState 的值。
🌐 An Integer constant equal to 1, the readyState value once the connection
is established.
WebSocket.CLOSING 只读
🌐 WebSocket.CLOSING Readonly
一个 Integer 常量等于 2,在关闭握手进行时的 readyState 值。
🌐 An Integer constant equal to 2, the readyState value while the closing
handshake is in progress.
WebSocket.CLOSED 只读
🌐 WebSocket.CLOSED Readonly
一个等于 3 的 Integer 常量,连接关闭后 readyState 的值。
🌐 An Integer constant equal to 3, the readyState value once the connection
is closed.
实例属性
🌐 Instance Properties
ws.url 只读
🌐 ws.url Readonly
一个 string,表示连接的解析 URL。
🌐 A string representing the resolved URL of the connection.
ws.readyState 只读
🌐 ws.readyState Readonly
一个 Integer,表示连接的当前状态:可以是 WebSocket.CONNECTING (0)、WebSocket.OPEN (1)、WebSocket.CLOSING (2) 或 WebSocket.CLOSED (3)。
🌐 An Integer representing the current state of the connection: one of
WebSocket.CONNECTING (0), WebSocket.OPEN (1), WebSocket.CLOSING
(2), or WebSocket.CLOSED (3).
ws.bufferedAmount 只读
🌐 ws.bufferedAmount Readonly
一个 Integer,表示已经通过 send() 排队但尚未交给网络的应用数据字节数。
🌐 An Integer representing the number of bytes of application data that have
been queued via send() but not yet handed off to the network.
ws.protocol 只读
🌐 ws.protocol Readonly
一个 string,包含服务器选择的子协议。在连接打开之前,或者如果服务器没有选择子协议,则为空字符串。
🌐 A string containing the subprotocol selected by the server. The empty string
until the connection is open or if the server did not select a subprotocol.
ws.extensions 只读
🌐 ws.extensions Readonly
一个包含服务器协商的扩展(例如 permessage-deflate)的 string。
🌐 A string containing the extensions negotiated by the server (for example
permessage-deflate).
ws.binaryType
string 控制 message 事件上如何暴露传入的二进制消息。可以是 nodebuffer、arraybuffer 或 blob。默认是 nodebuffer。
🌐 A string controlling how incoming binary messages are exposed on the
message event. Can be nodebuffer, arraybuffer, or blob. The default is
nodebuffer.
'nodebuffer' 是一个 Electron 扩展,用于将二进制消息作为 Buffer 对象传递,这通常是在主进程中最方便的表示方式。将 binaryType 设置为 'arraybuffer' 或 'blob',即可获得与渲染器 WebSocket 相同的行为。
ws.onopen
open 事件的 Function | null 事件处理器。相当于调用 addEventListener('open', ...)。
🌐 A Function | null event handler for the open event. Equivalent to calling
addEventListener('open', ...).
ws.onmessage
message 事件的 Function | null 事件处理器。相当于调用 addEventListener('message', ...)。
🌐 A Function | null event handler for the message event. Equivalent to
calling addEventListener('message', ...).
ws.onerror
error 事件的 Function | null 事件处理器。相当于调用 addEventListener('error', ...)。
🌐 A Function | null event handler for the error event. Equivalent to calling
addEventListener('error', ...).
ws.onclose
close 事件的 Function | null 事件处理器。相当于调用 addEventListener('close', ...)。
🌐 A Function | null event handler for the close event. Equivalent to calling
addEventListener('close', ...).
实例方法
🌐 Instance Methods
ws.send(data)
datastring | ArrayBufferLike | ArrayBufferView | Blob - 要发送的数据。字符串会作为文本帧发送;其他所有内容都会作为二进制帧发送。
将 data 入队以发送到服务器。如果 readyState 是 CONNECTING,则会抛出 InvalidStateError DOMException。
🌐 Enqueues data to be transmitted to the server. Throws an
InvalidStateError DOMException if readyState is CONNECTING.
ws.close([code][, reason])
codeInteger(optional)- WebSocket 关闭代码。必须是1000或在3000–4999范围内。reasonstring(optional)- 一个人类可读的关闭原因。必须编码为不超过123字节的UTF-8。
关闭连接。在仍然处于 CONNECTING 状态时调用 close() 会中止握手。
🌐 Closes the connection. Calling close() while still CONNECTING aborts the
handshake.
事件
🌐 Events
net.WebSocket 是一个 EventTarget,不是 EventEmitter。使用 addEventListener() 或相应的 on* 事件处理属性来监听:
open- 当连接建立并且握手完成时触发此事件。此事件之后,protocol和extensions会反映与服务器协商的值。message- 当消息到达时,会发出一个MessageEvent。event.data是文本帧的string,或者是二进制帧的Buffer、ArrayBuffer或Blob(根据binaryType)。error- 连接失败时触发。之后总会紧跟一个close事件。close- 当连接因任何原因关闭时,会触发CloseEvent(code,reason,wasClean)。当连接失败(例如握手被拒绝或网络不可达)时,code为1006,Electron 会将reason设置为底层网络错误的简短描述,这样即使没有调试器,也能诊断出失败原因。