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 upgrade request from http and shake hands, generate WebSocket object

1
static Handler ws.upgrade(Function accept);

Call parameters:

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

Return result:


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

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

Call parameters:

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

Return result:

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

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

constant

CONTINUE

Specify websocket message type 0, representing a continue frame

1
const ws.CONTINUE = 0;

TEXT

Specify websocket message type 1, representing a text frame

1
const ws.TEXT = 1;

BINARY

Specify websocket message type 2, representing 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, representing a pong frame

1
const ws.PONG = 10;

CONNECTING

Specifies the WebSocket state, indicating that it is connecting

1
const ws.CONNECTING = 0;

OPEN

Specify the WebSocket state, indicating the open state

1
const ws.OPEN = 1;

CLOSING

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

1
const ws.CLOSING = 2;

CLOSED

Specify the WebSocket state, indicating that it has been closed

1
const ws.CLOSED = 3;