Module basic module

Module ws

websocket support module

Instructions:

1
var ws = require('ws');

Create a server:

1 2 3 4 5 6 7 8 9
var ws = require('ws'); var http = require('http'); var svr = new http.Server(80, { '/ws': ws.upgrade((conn, req) => { conn.onmessage = e => console.log(e.data); }) }); svr.run();

Use WebSocket client:

1 2 3 4
var ws = require('ws'); var conn = new ws.Socket('ws://127.0.0.1/ws'); conn.onmessage = e => console.log(e.data);

Object

Message

Create a websocket message object, see WebSocketMessage

1
WebSocketMessage ws.Message;

Socket

WebSocket object, see WebSocket

1
WebSocket ws.Socket;

Static function

upgrade

Create a websocket protocol processor, receive an upgrade request from http and shake hands, and generate a WebSocket object

1
static Handler ws.upgrade(Function accept);

Call parameters:

  • accept : Function, the connection success processing function, the callback will pass two parameters, the first parameter is the received WebSocket object, and the second parameter is the HttpRequest object during the handshake

Return result:


Create a websocket protocol processor, receive an upgrade request from http and shake hands, and generate a WebSocket object

1 2
static Handler ws.upgrade(Object opts, Function accept);

Call parameters:

  • opts : Object, connection options, the default is {}
  • accept : Function, the connection success processing function, the callback will pass two parameters, the first parameter is the received WebSocket object, and the second parameter is the HttpRequest object during the handshake

Return result:

opts contains additional options requested, and the supported content is as follows:

1 2 3 4
{ "perMessageDeflate": true, // 指定是否支持压缩,缺省支持 "maxPayload": 67108864 // 指定最大数据包尺寸,缺省为 67108864 }

constant

CONTINUE

Specify websocket message type 0, which represents a continuation frame

1
const ws.CONTINUE = 0;

TEXT

Specify websocket message type 1, which represents a text frame

1
const ws.TEXT = 1;

BINARY

Specify websocket message type 2, which represents a binary frame

1
const ws.BINARY = 2;

CLOSE

Specify websocket message type 8, the connection is closed

1
const ws.CLOSE = 8;

PING

Specify websocket message type 9, which represents a ping frame

1
const ws.PING = 9;

PONG

Specify websocket message type 10, which represents a pong frame

1
const ws.PONG = 10;

CONNECTING

Specify the WebSocket status, indicating that it is connecting

1
const ws.CONNECTING = 0;

OPEN

Specify WebSocket state, which means open state

1
const ws.OPEN = 1;

CLOSING

Specify the WebSocket status, indicating that the CLOSE message has been sent, waiting to be closed

1
const ws.CLOSING = 2;

CLOSED

Specify the WebSocket status, indicating that it has been closed

1
const ws.CLOSED = 3;