ws

Table of Contents目录

Class: WebSocketServer

This class represents a WebSocket server. It extends the EventEmitter.此类表示WebSocket服务器。它扩展了EventEmitter

new WebSocketServer(options[, callback])

Create a new server instance. One and only one of port, server or noServer must be provided or an error is thrown. 创建一个新的服务器实例。必须提供portservernoServer中的一个,否则将引发错误。An HTTP server is automatically created, started, and used if port is set. 如果设置了port,则会自动创建、启动和使用HTTP服务器。To use an external HTTP/S server instead, specify only server or noServer. In this case the HTTP/S server must be started manually. 若要使用外部HTTP/S服务器,请仅指定servernoServer。在这种情况下,必须手动启动HTTP/S服务器。The "noServer" mode allows the WebSocket server to be completely detached from the HTTP/S server. This makes it possible, for example, to share a single HTTP/S server between multiple WebSocket servers.“noServer”模式允许WebSocket服务器与HTTP/S服务器完全分离。例如,这使得在多个WebSocket服务器之间共享单个HTTP/S服务器成为可能。

NOTE: Use of verifyClient is discouraged. Rather handle client authentication in the 'upgrade' event of the HTTP server. See examples for more details.不鼓励使用verifyClient。而是在HTTP服务器的'upgrade'事件中处理客户端身份验证。有关更多详细信息,请参阅示例。

If verifyClient is not set then the handshake is automatically accepted. 如果未设置verifyClient,则会自动接受握手。If it has a single parameter then ws will invoke it with the following argument:如果它只有一个参数,那么ws将使用以下参数调用它:

The return value (Boolean) of the function determines whether or not to accept the handshake.函数的返回值(Boolean)决定是否接受握手。

If verifyClient has two parameters then ws will invoke it with the following arguments:如果verifyClient有两个参数,那么ws将使用以下参数调用它:

handleProtocols takes two arguments:采用两个参数:

The returned value sets the value of the Sec-WebSocket-Protocol header in the HTTP 101 response. If returned value is false the header is not added in the response.返回的值设置HTTP 101响应中Sec-WebSocket-Protocol标头的值。如果返回值为false,则不会在响应中添加标头。

If handleProtocols is not set then the first of the client's requested subprotocols is used.如果未设置handleProtocols,则使用客户端请求的第一个子协议。

perMessageDeflate can be used to control the behavior of permessage-deflate extension. 可用于控制渗透性放气扩展的行为。The extension is disabled when false (default value). If an object is provided then that is extension parameters:当为false(默认值)时,扩展被禁用。如果提供了一个对象,那么这就是扩展参数:

If a property is empty then either an offered configuration or a default value is used. When sending a fragmented message the length of the first fragment is compared to the threshold. 如果属性为空,则使用提供的配置或默认值。当发送分段消息时,将第一分段的长度与阈值进行比较。This determines if compression is used for the entire message.这将确定是否对整个消息使用压缩。

callback will be added as a listener for the 'listening' event on the HTTP server when the port option is set.当设置port选项时,callback将被添加为HTTP服务器上'listening'事件的侦听器。

Event: 'close'

Emitted when the server closes. This event depends on the 'close' event of HTTP server only when it is created internally. In all other cases, the event is emitted independently.在服务器关闭时发出。仅当HTTP服务器的'close'事件在内部创建时,此事件才依赖于该事件。在所有其他情况下,事件都是独立发出的。

Event: 'connection'

Emitted when the handshake is complete. request is the http GET request sent by the client. Useful for parsing authority headers, cookie headers, and other information.握手完成时发出。request是客户端发送的http GET请求。用于解析权限标头、cookie标头和其他信息。

Event: 'error'

Emitted when an error occurs on the underlying server.当基础服务器上发生错误时发出。

Event: 'headers'

Emitted before the response headers are written to the socket as part of the handshake. This allows you to inspect/modify the headers before they are sent.在响应标头作为握手的一部分写入套接字之前发出。这允许您在发送邮件头之前检查/修改邮件头。

Event: 'listening'

Emitted when the underlying server has been bound.在绑定基础服务器时发出。

Event: 'wsClientError'

Emitted when an error occurs before the WebSocket connection is established. 在建立WebSocket连接之前发生错误时发出。socket and request are respectively the socket and the HTTP request from which the error originated. socketrequest分别是产生错误的套接字和HTTP请求。The listener of this event is responsible for closing the socket. When the 'wsClientError' event is emitted there is no http.ServerResponse object, so any HTTP response, including the response headers and body, must be written directly to the socket. 此事件的侦听器负责关闭套接字。发出'wsClientError'事件时,没有http.ServerResponse对象,因此任何HTTP响应(包括响应标头和正文)都必须直接写入socketIf there is no listener for this event, the socket is closed with a default 4xx response containing a descriptive error message.如果没有此事件的侦听器,则套接字将关闭,并使用包含描述性错误消息的默认4xx响应。

server.address()

Returns an object with port, family, and address properties specifying the bound address, the address family name, and port of the server as reported by the operating system if listening on an IP socket. 返回一个对象,该对象具有portfamilyaddress属性,指定绑定地址、地址系列名称和操作系统在侦听IP套接字时报告的服务器端口。If the server is listening on a pipe or UNIX domain socket, the name is returned as a string.如果服务器正在侦听管道或UNIX域套接字,则名称将作为字符串返回。

server.clients

A set that stores all connected clients. This property is only added when the clientTracking is truthy.存储所有连接的客户端的集合。只有当clientTracking为truthy时,才会添加此属性。

server.close([callback])

Prevent the server from accepting new connections and close the HTTP server if created internally. 阻止服务器接受新连接,并关闭内部创建的HTTP服务器。If an external HTTP server is used via the server or noServer constructor options, it must be closed manually. 如果通过servernoServer构造函数选项使用外部HTTP服务器,则必须手动关闭该服务器。Existing connections are not closed automatically. The server emits a 'close' event when all connections are closed unless an external HTTP server is used and client tracking is disabled. 现有连接不会自动关闭。除非使用外部HTTP服务器并且禁用了客户端跟踪,否则当所有连接都关闭时,服务器会发出'close'事件。In this case the 'close' event is emitted in the next tick. 在这种情况下,'close'事件将在下一个刻度中发出。The optional callback is called when the 'close' event occurs and receives an Error if the server is already closed.'close'事件发生时调用可选回调,如果服务器已经关闭,则会收到Error

server.handleUpgrade(request, socket, head, callback)

Handle a HTTP upgrade request. When the HTTP server is created internally or when the HTTP server is passed via the server option, this method is called automatically. 处理HTTP升级请求。当HTTP服务器是在内部创建的,或者当HTTP服务器通过server选项传递时,会自动调用此方法。When operating in "noServer" mode, this method must be called manually.在“noServer”模式下操作时,必须手动调用此方法。

If the upgrade is successful, the callback is called with two arguments:如果升级成功,则使用两个参数调用callback

server.shouldHandle(request)

See if a given request should be handled by this server. By default this method validates the pathname of the request, matching it against the path option if provided. 查看给定的请求是否应由该服务器处理。默认情况下,此方法验证请求的路径名,并将其与提供的路径path进行匹配。The return value, true or false, determines whether or not to accept the handshake.返回值truefalse决定是否接受握手。

This method can be overridden when a custom handling logic is required.当需要自定义处理逻辑时,可以重写此方法。

Class: WebSocket

This class represents a WebSocket. It extends the EventEmitter.这个类表示一个WebSocket。它扩展了EventEmitter

Ready state constants就绪状态常数

Constant Value Description
CONNECTING 0 The connection is not yet open.连接尚未打开。
OPEN 1 The connection is open and ready to communicate.连接已打开,可以进行通信。
CLOSING 2 The connection is in the process of closing.连接正在关闭过程中。
CLOSED 3 The connection is closed.连接已关闭。

new WebSocket(address[, protocols][, options])

Create a new WebSocket instance.创建一个新的WebSocket实例。

perMessageDeflate default value is true. 默认值为trueWhen using an object, parameters are the same of the server. The only difference is the direction of requests. 使用对象时,参数与服务器相同。唯一的区别是请求的方向。For example, serverNoContextTakeover can be used to ask the server to disable context takeover.例如,serverNoContextTakeover可用于要求服务器禁用上下文接管。

finishRequest is called with arguments使用参数调用finishRequest

for each HTTP GET request (the initial one and any caused by redirects) when it is ready to be sent, to allow for last minute customization of the headers. 当每个HTTP GET请求(初始请求和任何由重定向引起的请求)准备好发送时,允许在最后一分钟自定义标头。If finishRequest is set then it has the responsibility to call request.end() once it is done setting request headers. 如果设置了finishRequest,那么一旦设置完请求头,它就有责任调用request.end()This is intended for niche use-cases where some headers can't be provided in advance e.g. because they depend on the underlying socket.这适用于一些无法提前提供头部的利基用例,例如,因为它们依赖于底层套接字。

IPC connections

ws supports IPC connections. To connect to an IPC endpoint, use the following URL form:ws支持IPC连接。要连接到IPC端点,请使用以下URL形式:

The character : is the separator between the IPC path (the Unix domain socket path or the Windows named pipe) and the URL path. 字符:是IPC路径(Unix域套接字路径或Windows命名管道)和URL路径之间的分隔符。The IPC path must not include the characters : and ?, otherwise the URL is incorrectly parsed. If the URL path is omittedIPC路径不得包含以下字符:?,否则URL解析错误。如果省略URL路径

ws+unix:/absolute/path/to/uds_socket

it defaults to /.它默认为/

Event: 'close'

Emitted when the connection is closed. code is a numeric value indicating the status code explaining why the connection has been closed. 当连接关闭时发出。code是一个数字值,表示解释连接关闭原因的状态代码。reason is a Buffer containing a human-readable string explaining why the connection has been closed.reasonBuffer包含一个人类可读的字符串,解释连接关闭的原因。

Event: 'error'

Emitted when an error occurs. Errors may have a .code property, matching one of the string values defined below under Error codes.发生错误时发出。错误可能具有.code属性,该属性与下面在错误代码下定义的字符串值之一相匹配。

Event: 'message'

Emitted when a message is received. data is the message content. isBinary specifies whether the message is binary or not.收到消息时发出。data是消息内容。isBinary指定消息是否为二进制。

Event: 'open'

Emitted when the connection is established.建立连接时发出。

Event: 'ping'

Emitted when a ping is received.当接收到ping时发出。

Event: 'pong'

Emitted when a pong is received.当接收到乒乓球时发出。

Event: 'redirect'

Emitted before a redirect is followed.在遵循重定向之前发出。 url is the redirect URL. request is the HTTP GET request with the headers queued. url是重定向url。request是具有排队头的HTTP GET请求。This event gives the ability to inspect confidential headers and remove them on a per-redirect basis using the request.getHeader() and request.removeHeader() API. 此事件使您能够检查机密标头,并使用request.getHeader()request.removeHeader()API逐个直接删除它们。The request object should be used only for this purpose. request对象只能用于此目的。When there is at least one listener for this event, no header is removed by default, even if the redirect is to a different domain.当此事件至少有一个侦听器时,即使重定向到不同的域,默认情况下也不会删除任何标头。

Event: 'unexpected-response'

Emitted when the server response is not the expected one, for example a 401 response. 当服务器响应不是预期响应时发出,例如401响应。This event gives the ability to read the response in order to extract useful information. If the server sends an invalid response and there isn't a listener for this event, an error is emitted.此事件提供读取响应以提取有用信息的能力。如果服务器发送了一个无效的响应,而没有此事件的侦听器,则会发出错误。

Event: 'upgrade'

Emitted when response headers are received from the server as part of the handshake. This allows you to read headers from the server, for example 'set-cookie' headers.当作为握手的一部分从服务器接收到响应标头时发出。这允许您从服务器读取标头,例如“set cookie”标头。

websocket.addEventListener(type, listener[, options])

Register an event listener emulating the EventTarget interface. 注册一个模拟EventTarget接口的事件侦听器。This method does nothing if type is not one of 'close', 'error', 'message', or 'open'.如果type不是'close''error''message''open'之一,则此方法不执行任何操作。

websocket.binaryType

A string indicating the type of binary data being transmitted by the connection. 一个字符串,指示连接所传输的二进制数据的类型。This should be one of "nodebuffer", "arraybuffer" or "fragments". Defaults to "nodebuffer". Type "fragments" will emit the array of fragments as received from the sender, without copyfull concatenation, which is useful for the performance of binary protocols transferring large messages with multiple fragments.这应该是“nodebuffer”、“arraybuffer”或“fragments”中的一个。默认为“nodebuffer”。类型“fragments”将发出从发送方接收到的片段数组,而不进行完全复制级联,这对于传输具有多个片段的大型消息的二进制协议的性能非常有用。

websocket.bufferedAmount

The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network. This deviates from the HTML standard in the following ways:已使用send()调用排队但尚未传输到网络的数据字节数。这在以下方面偏离了HTML标准:

  1. If the data is immediately sent the value is 0.如果立即发送数据,则值为0
  2. All framing bytes are included.包括所有成帧字节。

websocket.close([code[, reason]])

Initiate a closing handshake.开始握手。

websocket.isPaused

Indicates whether the websocket is paused.指示是否暂停Web套接字。

websocket.extensions

An object containing the negotiated extensions.包含协商扩展的对象。

websocket.onclose

An event listener to be called when connection is closed. The listener receives a CloseEvent named "close".连接关闭时要调用的事件侦听器。侦听器接收一个名为“close”的CloseEvent

websocket.onerror

An event listener to be called when an error occurs. The listener receives an ErrorEvent named "error".发生错误时要调用的事件侦听器。侦听器接收一个名为“error”的ErrorEvent

websocket.onmessage

An event listener to be called when a message is received. The listener receives a MessageEvent named "message".接收到消息时要调用的事件侦听器。侦听器接收一个名为“message”的MessageEvent

websocket.onopen

An event listener to be called when the connection is established. The listener receives an OpenEvent named "open".建立连接时要调用的事件侦听器。侦听器接收一个名为“open”的OpenEvent

websocket.pause()

Pause the websocket causing it to stop emitting events. Some events can still be emitted after this is called, until all buffered data is consumed. 暂停websocket,使其停止发出事件。在调用之后,一些事件仍然可以发出,直到所有缓冲的数据都被消耗掉。This method is a noop if the ready state is CONNECTING or CLOSED.如果就绪状态为CONNECTINGCLOSED,则此方法为noop。

websocket.ping([data[, mask]][, callback])

Send a ping. This method throws an error if the ready state is CONNECTING.发送ping。如果就绪状态为CONNECTING,此方法将抛出一个错误。

websocket.pong([data[, mask]][, callback])

Send a pong. This method throws an error if the ready state is CONNECTING.发一个乒乓球。如果就绪状态为CONNECTING,此方法将抛出一个错误。

websocket.protocol

The subprotocol selected by the server.服务器选择的子协议。

websocket.resume()

Make a paused socket resume emitting events. This method is a noop if the ready state is CONNECTING or CLOSED.使暂停的套接字继续发射事件。如果就绪状态为CONNECTINGCLOSED,则此方法为noop。

websocket.readyState

The current state of the connection. This is one of the ready state constants.连接的当前状态。这是就绪状态常数之一。

websocket.removeEventListener(type, listener)

Removes an event listener emulating the EventTarget interface. 删除模拟EventTarget接口的事件侦听器。This method only removes listeners added with websocket.addEventListener().此方法仅删除使用websocket.addEventListener()添加的侦听器。

websocket.send(data[, options][, callback])

Send data through the connection. This method throws an error if the ready state is CONNECTING.通过连接发送data。如果就绪状态为CONNECTING,此方法将抛出一个错误。

websocket.terminate()

Forcibly close the connection. Internally this calls socket.destroy().强行关闭连接。在内部,这会调用socket.destroy()

websocket.url

The URL of the WebSocket server. Server clients don't have this attribute.WebSocket服务器的URL。服务器客户端没有此属性。

createWebSocketStream(websocket[, options])

Returns a Duplex stream that allows to use the Node.js streams API on top of a given WebSocket.返回一个Duplex流,该流允许在给定的WebSocket上使用Node.js流API。

Environment variables环境变量

WS_NO_BUFFER_UTIL

When set to a non empty value, prevents the optional bufferutil dependency from being required.当设置为非空值时,将防止需要可选的bufferutil依赖项。

WS_NO_UTF_8_VALIDATE

When set to a non empty value, prevents the optional utf-8-validate dependency from being required.当设置为非空值时,可防止需要可选的utf-8-validate依赖项。

Error codes

Errors emitted by the websocket may have a .code property, describing the specific type of error that has occurred:websocket发出的错误可能有一个.code属性,用于描述发生的特定类型的错误:

WS_ERR_EXPECTED_FIN

A WebSocket frame was received with the FIN bit not set when it was expected.收到的WebSocket帧的FIN位未按预期设置。

WS_ERR_EXPECTED_MASK

An unmasked WebSocket frame was received by a WebSocket server.WebSocket服务器接收到未屏蔽的WebSocket帧。

WS_ERR_INVALID_CLOSE_CODE

A WebSocket close frame was received with an invalid close code.收到的WebSocket关闭帧包含无效的关闭代码。

WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH

A control frame with an invalid payload length was received.接收到具有无效有效负载长度的控制帧。

WS_ERR_INVALID_OPCODE

A WebSocket frame was received with an invalid opcode.收到的WebSocket帧具有无效的操作码。

WS_ERR_INVALID_UTF8

A text or close frame was received containing invalid UTF-8 data.收到包含无效UTF-8数据的文本或闭合帧。

WS_ERR_UNEXPECTED_MASK

A masked WebSocket frame was received by a WebSocket client.WebSocket客户端接收到屏蔽的WebSocket帧。

WS_ERR_UNEXPECTED_RSV_1

A WebSocket frame was received with the RSV1 bit set unexpectedly.收到一个WebSocket帧,其中意外设置了RSV1位。

WS_ERR_UNEXPECTED_RSV_2_3

A WebSocket frame was received with the RSV2 or RSV3 bit set unexpectedly.收到一个WebSocket帧,其中意外设置了RSV2或RSV3位。

WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH

A data frame was received with a length longer than the max supported length (2^53 - 1, due to JavaScript language limitations).收到的数据帧的长度大于支持的最大长度(2^53-1,由于JavaScript语言限制)。

WS_ERR_UNSUPPORTED_MESSAGE_LENGTH

A message was received with a length longer than the maximum supported length, as configured by the maxPayload option.收到的消息长度超过了maxPayload选项所配置的支持的最大长度。