WebSocket $websocket Bob 1.6.0+ 可用
插件可通过 $websocket API 进行 WebSocket 连接。
$websocket.new(object)
创建一个 WebSocket 连接。
参数是一个 object 类型,可具有以下属性:
| 参数 | 类型 | 说明 |
|---|---|---|
| url | string | 请求链接 |
| allowSelfSignedSSLCertificates | boolean | 允许自签名 SSL 证书 |
| timeoutInterval | number | 请求超时时间,默认 60 秒 |
| header | object | 请求头,key 和 value 都必须是 string 类型 |
返回值是 WebSockt 对象。
使用示例:
js
var socket = $websocket.new({
url: "wss://xx.com",
allowSelfSignedSSLCertificates: true,
timeoutInterval: 100,
header: {
"Sec-WebSocket-Protocol": "someother protocols",
"Sec-WebSocket-Version": "14",
}
})socket.readyState
socket 连接状态,number 类型。
| 值 | 状态 |
|---|---|
| 0 | connecting |
| 1 | open |
| 2 | closing |
| 3 | closed |
js
var state = socket.readyStatesocket.open()
打开 WebSocket 连接。
socket.close(object)
关闭 WebSocket 连接。
参数是一个 object 类型,可具有以下属性:
| 参数 | 类型 | 说明 |
|---|---|---|
| code | number | 关闭连接代码,可不传,参考 https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4 |
js
socket.close()socket.sendString(string)
发送文本。
js
socket.sendString("hello world");socket.sendData(data)
发送二进制数据。
js
socket.sendData($data.fromUTF8("good job"));socket.ping(data)
socket.ping()socket.pong(data)
socket.pong()socket.listenOpen(function)
监听打开连接。
js
socket.listenOpen(function (socket) {
$log.info(`did open`);
})socket.listenClose(function)
监听关闭连接。
js
socket.listenClose(function (socket, code, reason) {
$log.info(`did close: code=${code}; reason=${reason}`);
})socket.listenError(function)
监听错误。
js
socket.listenError(function (socket, error) {
$log.info(`did error: code=${error.code}; message=${error.message}; type=${error.type}`);
})socket.listenReceiveString(function)
监听收到文本。
js
socket.listenReceiveString(function (socket, string) {
$log.info(`did receive string: ${string}`);
})socket.listenReceiveData(function)
监听收到二进制数据。
js
socket.listenReceiveData(function (socket, data) {
$log.info(`did receive data: length=${data.length}`);
})socket.listenReceivePing(function)
监听收到 ping。
js
socket.listenReceivePing(function (socket, data) {
$log.info(`did receive ping: length=${data.length}`);
})socket.listenReceivePong(function)
监听收到 pong。
js
socket.listenReceivePong(function (socket, data) {
$log.info(`did receive pong: length=${data.length}`);
})
