WS API Document

Class: WebSocketServer

class WebSocket.Server({host, port, server, noServer...}[, callback])

本类代表一个WebSocket服务。它扩展自 EventEmitter

new WebSocket.Server(options[, callback])

Create a new server instance. One of port, server or noServer must be provided or an error is thrown.

参数
  • host (String()) – The hostname where to bind the server.

  • port (Number()) – The port where to bind the server.

  • backlog (Number()) – The maximum length of the queue of pending connections.

  • server (http.Server | https.Server()) – A pre-created Node.js HTTP/S server.

  • verifyClient (Function()) – 一个用来验证接入有效性的函数。详情如下:

  • handleProtocols (Function()) – A function which can be used to handle the WebSocket subprotocols. See description below.

  • path (String()) – Accept only connections matching this path.

  • noServer (Boolean()) – Enable no server mode.

  • clientTracking (Boolean()) – Specifies whether or not to track clients.

  • perMessageDeflate (Boolean | Object()) –

    Enable/disable permessage-deflate.

    perMessageDeflate can be used to control the behavior of permessage-deflate extension. he extension is disabled when false (default value).

    If an object is provided then that is extension parameters:

    • serverNoContextTakeover: (Boolean) - Whether to use context takeover or not.

    • clientNoContextTakeover: (Boolean) - Acknowledge disabling of client context takeover.

    • serverMaxWindowBits: (Number) - The value of windowBits.

    • clientMaxWindowBits: (Number) - Request a custom client window size.

    • zlibDeflateOptions: (Object) - Additional options <zlib-options>`_ to pass to zlib on deflate.

    • zlibInflateOptions: (Object) - Additional options <zlib-options>`_ to pass to zlib on inflate.

    • threshold: (Number) - Payloads smaller than this will not be compressed. Defaults to 1024 bytes.

    • concurrencyLimit: (Number) - The number of concurrent calls to zlib. Calls above this limit will be queued. Default 10. You usually won’t need to touch this option. See this issue for more details.

  • maxPayload (Number()) – The maximum allowed message size in bytes.

  • callback (Function()) – callback will be added as a listener for the listening event on the HTTP server when not operating in “noServer” mode.

An HTTP server is automatically created, started, and used if port is set.

To use an external HTTP/S server instead, specify only server or noServer. In this case the HTTP/S server must be started manually. The “noServer” mode allows the WebSocket server to be completly detached from the HTTP/S server. This makes it possible, for example, to share a single HTTP/S server between multiple WebSocket servers.

If verifyClient is not set then the handshake is automatically accepted.

handleProtocols(protocols, request)
参数
  • protocols (Array()) – The list of WebSocket subprotocols indicated by the client in the Sec-WebSocket-Protocol header.

  • request (http.IncomingMessage()) – The client HTTP GET request.

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.

If handleProtocols is not set then the first of the client’s requested subprotocols is used.

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.

ws.onEvent.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.

ws.onEvent.connection(socket, request)

Emitted when the handshake is complete.

Useful for parsing authority headers, cookie headers, and other information.

参数
  • socket (WebSocket()) –

  • request (http.IncomingMessage()) – the http GET request sent by the client.

ws.onEvent.error()
参数
  • error (Error()) – Emitted when an error occurs on the underlying server.

ws.onEvent.headers(headers, request)

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.

参数
  • headers (Array()) –

  • request (http.IncomingMessage()) –

ws.onEvent.listening()

当底层服务器被绑定时发出。

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.

If the server is listening on a pipe or UNIX domain socket, the name is returned as a string.

server.clients

Please note that this property is only added when the clientTracking is truthy.

Return

A set that stores all connected clients.

Rtype

Set

server.close([callback])

Close the HTTP server if created internally, terminate all clients and call callback when done.

If an external HTTP server is used via the server or noServer constructor options, it must be closed manually.

server.handleUpgrade(request, socket, head, callback)
参数
  • request (http.IncomingMessage()) – The client HTTP GET request.

  • socket (net.Socket()) – The network socket between the server and client.

  • head (Buffer()) – The first packet of the upgraded stream.

  • callback (Function(WebSocket)()) – If the upgrade is successful, the callback is called with a WebSocket object as parameter.

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.

When operating in “noServer” mode, this method must be called manually.

server.shouldHandle(request)
参数
  • request (http.IncomingMessage()) – The client HTTP GET 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.

The return value, true or false, determines whether or not to accept the handshake.

This method can be overridden when a custom handling logic is required.

Class: WebSocket

This class represents a WebSocket. It extends the EventEmitter.

准备好的状态常量

常量

描述

CONNECTING

0

连接未打开

OPEN

1

连接已打开并准备交流

CLOSING

2

连接关闭中

CLOSED

3

连接已关闭

class WebSocket(address[, protocols][, {followRedirects,...}])

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

参数
  • address (String | url.URL()) – 连接用的URL

  • protocols (String | Array()) – The list of subprotocols.

  • followRedirects (Boolean()) – Whether or not to follow redirects. Defaults to false.

  • handshakeTimeout (Number()) – Timeout in milliseconds for the handshake request. This is reset after every redirection.

  • maxPayload (Number()) – The maximum allowed message size in bytes.

  • maxRedirects (Number()) – The maximum number of redirects allowed. Defaults to 10.

  • origin (String()) – Value of the Origin or Sec-WebSocket-Origin header depending on the protocolVersion.

  • perMessageDeflate (Boolean(true) | Object()) – Enable/disable permessage-deflate. perMessageDeflate default value is true. When 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.

  • protocolVersion (Number()) – Value of the Sec-WebSocket-Version header.

  • skipUTF8Validation (Boolean()) – Specifies whether or not to skip UTF-8 validation for text and close messages. Defaults to false. Set to true only if the server is trusted.

  • other (Any other option allowed in http.request() or https.request()) – Options given do not have any effect if parsed from the URL given with the address parameter.

Create a new WebSocket instance.

UNIX Domain Sockets

ws supports making requests to UNIX domain sockets. To make one, use the following URL scheme:

ws+unix:///absolute/path/to/uds_socket:/pathname?search_params

备注

that : is the separator between the socket path and the URL path. If the URL path is omitted

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

it defaults to /.

ws.onEvent.close()

Emitted when the connection is closed.

参数
  • code (Number()) – a numeric value indicating the status code explaining why the connection has been closed.

  • reason (String()) – a human-readable string explaining why the connection has been closed.

ws.onEvent.error()
参数
  • error (Error()) – Emitted when an error occurs.

ws.onEvent.message()
参数
  • data (String|Buffer|ArrayBuffer|Buffer[]()) – Emitted when a message is received from the server.

ws.onEvent.open()

Emitted when the connection is established.

ws.onEvent.ping()
参数
  • data (Buffer()) –

Emitted when a ping is received from the server.

ws.onEvent.pong()
参数
  • data (Buffer()) –

Emitted when a pong is received from the server.

ws.onEvent.unexpected-response()
参数
  • request (http.ClientRequest()) –

  • response (http.IncomingMessage()) –

Emitted when the server response is not the expected one, for example a 401 response.

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.

ws.onEvent.upgrade()
参数
  • response (http.IncomingMessage()) –

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.

websocket.addEventListener(type, listener)
参数
  • type (String()) – A string representing the event type to listen for.

  • listener (Function()) – The listener to add.

Register an event listener emulating the EventTarget interface.

websocket.binaryType
Return

A string indicating the type of binary data being transmitted by the connection.

Rtype

String

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.

websocket.bufferedAmount
Return

The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.

Rtype

Number

websocket.close([code[, reason]])
参数
  • code – Number} A numeric value indicating the status code explaining why the connection is being closed.

  • reason – String} A human-readable string explaining why the connection is closing.

Initiate a closing handshake.

websocket.extensions
Rtype

Object

Return

包含协商扩展的对象。

websocket.onclose()
返回类型

Function

返回

当连接关闭时调用事件监听器

The listener receives a CloseEvent named “close”.

websocket.onerror()
返回类型

Function

返回

发生错误时调用的事件

The listener receives an ErrorEvent named “error”.

websocket.onmessage()
返回类型

Function

返回

An event listener to be called when a message is received from the server.

The listener receives a MessageEvent named “message”.

websocket.onopen()
返回类型

Function

返回

An event listener to be called when the connection is established.

The listener receives an OpenEvent named “open”.

websocket.ping([data[, mask]][, callback])
参数
  • data (Any()) – 在ping结构中发送的数据

  • mask (Boolean()) – Specifies whether data should be masked or not. Defaults to true when websocket is not a server client.

  • callback (Function()) – An optional callback which is invoked when the ping frame is written out.

发送一个ping

websocket.pong([data[, mask]][, callback])
参数
  • data (Any()) – 在pong结构中发送的数据

  • mask (Boolean()) – Specifies whether data should be masked or not. Defaults to true when websocket is not a server client.

  • callback (Function()) – An optional callback which is invoked when the pong frame is written out.

发送一个pong

websocket.protocol
Return

服务器选择的subprotocal

Rtype

String

websocket.readyState
Rtype

Number

Return

当前链接状态。预备状态常量的一个。

websocket.removeEventListener(type, listener)
参数
  • type (String()) – 要删除的表示事件类型的字符

  • listener (Function()) – 要删除的监听器

Removes an event listener emulating the EventTarget interface.

websocket.send(data[, options][, callback])
参数
  • data (Any()) – 发送的数据

  • options (Object()) –

  • compress (Boolean()) – Specifies whether data should be compressed or not.Defaults to true when permessage-deflate is enabled.

  • binary (Boolean()) – Specifies whether data should be sent as a binary or not. Default is autodetected.

  • mask (Boolean()) – Specifies whether data should be masked or not. Defaults to true when websocket is not a server client.

  • fin (Boolean()) – Specifies whether data is the last fragment of a message or not. Defaults to true.

  • callback

    Function An optional callback which is invoked when data is written out.

    通过连接发送 data

websocket.terminate()

强制关闭连接

websocket.url
Rtype

String

Return

WebSocket 服务器的 URL。服务器客户端没有这个属性。

createWebSocketStream(websocket[, options])

createWebSocketStream(websocket[, options])
参数
  • websocket (WebSocket()) – 一个对象

  • options (Object()) – 通过双工构建传输选项

返回

返回一个双攻流允许在给定的WebSocket之上使用Node.js流接口

WS错误码

Errors emitted by the websocket may have a .code property, describing the specific type of error that has occurred:

WS_ERR_EXPECTED_FIN

A WebSocket frame was received with the FIN bit not set when it was expected.

WS_ERR_EXPECTED_MASK

An unmasked WebSocket frame was received by a WebSocket server.

WS_ERR_INVALID_CLOSE_CODE

A WebSocket close frame was received with an invalid close code.

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.

WS_ERR_INVALID_UTF8

A text or close frame was received containing invalid UTF-8 data.

WS_ERR_UNEXPECTED_MASK

A masked WebSocket frame was received by a WebSocket client.

WS_ERR_UNEXPECTED_RSV_1

A WebSocket frame was received with the RSV1 bit set unexpectedly.

WS_ERR_UNEXPECTED_RSV_2_3

A WebSocket frame was received with the RSV2 or RSV3 bit set unexpectedly.

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).

WS_ERR_UNSUPPORTED_MESSAGE_LENGTH

A message was received with a length longer than the maximum supported length, as configured by the maxPayload option.