Module ws
websocket support module
Instructions:
1var ws = require('ws');
Create a server:
1
2
3
4
5
6
7
8
9var 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
4var 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
1WebSocketMessage ws.Message;
Socket
WebSocket Object, see WebSocket
1WebSocket ws.Socket;
Static function
upgrade
Create a websocket protocol handler from http Receive upgrade request and shake hands, generate WebSocket Object
1static 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:
- Handler, Return to the protocol handler, which can be used with HttpServer, Chain, Routing Waiting for docking
`
Create a websocket protocol handler from http Receive upgrade request and shake hands, generate WebSocket Object
1
2static 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:
- Handler, Return to the protocol handler, which can be used with HttpServer, Chain, Routing Waiting for docking
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
1const ws.CONTINUE = 0;
TEXT
Specify websocket message type 1, which represents a text frame
1const ws.TEXT = 1;
BINARY
Specify websocket message type 2, which represents a binary frame
1const ws.BINARY = 2;
CLOSE
Specify websocket message type 8, the connection is closed
1const ws.CLOSE = 8;
PING
Specify websocket message type 9, which represents a ping frame
1const ws.PING = 9;
PONG
Specify websocket message type 10, which represents a pong frame
1const ws.PONG = 10;
CONNECTING
Specify WebSocket Status, indicating that it is connecting
1const ws.CONNECTING = 0;
OPEN
Specify WebSocket State, which means open state
1const ws.OPEN = 1;
CLOSING
Specify WebSocket Status, indicating that the CLOSE message has been sent, waiting to be closed
1const ws.CLOSING = 2;
CLOSED
Specify WebSocket Status, which means it is closed
1const ws.CLOSED = 3;