Create WS Server

1
2
3
4
5
6
7
8
// get WS Object
const WebSocket = require('ws')

// Create new Server Instance
const ws = new WebSocket.Server({
port: 80, // port
verifyClient: socketverify // (optional)function to verify connection
})

new WebSocket.Server(options[, callback])

1
2
3
4
5
6
7
8
9
10
11
12
13
options: {
host: string,
port: number,
backlog: number, // the maximum length of the queue of pending connection.
server: http.Server | https.Server, // a pre-created Node Http Server.
verifyClient: function, // a function which can be used to validate incoming connections.
handleProtocols: function, // a function which can be used to handle the WebSocket subprotocols.
path: string, // Accept only connections matching this path.
noServer: boolean, // Enable no server mode.
clientTracking: boolean, // Specifies whether or not track clients.
perMessageDeflate: boolean | object, // Enable/Disable permessage-deflate.
maxPayload: number, // Maximum allowed message size in bytes.
}

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

Set VerifyClient

1
2
3
4
5
6
7
8
function socketverify(info) {
// connect if return true
var origin = info.origin.match(/*...*/)
if (/*...*/) {
return true
}
return false
}

If verifyClient is not set then the handshake is automatically accepted. If it is is provided with a single argument then that is:

1
2
3
4
5
info: {
origin: string, // The value in the Origin header indicated by the client.
req: http.incomingMessage, // The client HTTP GET request.
secure: boolean, // `true` is `req.connection.authorized` or `req.connection.encrypted` is set.
}

If the verifyClient provided with 2 arguments, the second one is cb, which accepts result: boolean, code: number, name: string.

Handle Request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ws.on('connect', (socket) => {
// the socket is a connect to client
// usually you should push it in an array for management
socket.onmessage = message
socket.onclose = close
socket.onerror = error
socket.onopen = open
})

function message(msg) {
// ...
}
function error(err) {
// ...
}
function close() {
// ...
}
function open() {
// ...
}

Events

Methods

Sending msg

1
socket.send(data[, options[, callback]])
  • data: binary or string

  • options:

    • mask: true | false 是否使用掩码

    • binary: true | false 是否二进制流

    • compress: true | false 是否压缩

  • callback: 回调

close connection

1
socket.close([code], [data])
  • code: 返回一个状态码

  • data: 结束连接时发送的信息

pause

1
socket.pause()

resume

1
socket.resume()

PING

1
socket.ping([data], [options], [dontFailWhenClosed])
  • data: ping 的时候发送的信息

  • options: 同 send

  • dontFailWhenClosed: true | false // 如果连接断开, 是否抛出错误

PONG

1
socket.pong([data], [options], [dontFailWhenClosed])

Ping 和 Pong 的区别在于, 一个包含 ping 帧(0x9), 一个包含 pong 帧(0xA)

pong 是对于接到 ping 之后的回应, 让双方都知道连接还存在

stream

terminate