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.start();

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

1
static Handler ws.upgrade(Function accept);

Call parameters:

  • accept: Function, the function to handle the successful connection, the callback will pass two parameters, the first parameter is the received WebSocket Object, the second parameter is the handshake HttpRequest Object

Return result:


Create a websocket protocol handler from http Receive upgrade request and shake hands, generate WebSocket Object

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

Call parameters:

  • opts: Object, connection option, default is {}
  • accept: Function, the function to handle the successful connection, the callback will pass two parameters, the first parameter is the received WebSocket Object, the second parameter is the handshake HttpRequest Object

Return result:

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

1 2 3 4
{ "perMessageDeflate": false, // 指定是否支持压缩,缺省不支持 "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 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 WebSocket Status, indicating that the CLOSE message has been sent, waiting to be closed

1
const ws.CLOSING = 2;

CLOSED

Specify WebSocket Status, which means it is closed

1
const ws.CLOSED = 3;