WebSocket 用于浏览器、桌面页面或其他客户端与 BT 服务端保持实时双向通信。当前版本支持 WebSocket 服务端监听。
当前版本支持 WebSocket 服务端监听和 WebSocket 客户端连接。
server = net.listen({ type:'ws', bind:'127.0.0.1:8081', route:'/ws', on_connect:fn(socket){ socket.send('welcome') }, on_message:fn(socket, data){ socket.send('echo:' + data) }, on_close:fn(socket){ println('ws closed:' + socket.addr) }, on_error:fn(err){ println(err) } })
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| type | string | 是 | 无 | 固定为 ws |
| bind | string | 是 | 无 | 监听地址,格式为 host:port |
| route | string | 否 | /ws | WebSocket 握手路径 |
| on_connect | fn | 否 | 无 | 客户端连接后调用,参数为 socket |
| on_message | fn | 否 | 无 | 收到消息后调用,参数为 socket, data |
| on_close | fn | 否 | 无 | 连接关闭后调用,参数为 socket |
| on_error | fn | 否 | 无 | 后台任务出错时调用,参数为 err |
net.listen({type:'ws'}) 返回 WsServer。
| 字段/方法 | 类型 | 说明 |
|---|---|---|
| addr | string | 服务监听地址 |
| type | string | 固定为 ws |
| close() | fn | 关闭服务,返回 true |
回调中的 socket 为 WsSocket。
| 字段/方法 | 类型 | 说明 |
|---|---|---|
| addr | string | 客户端远端地址 |
| type | string | 固定为 ws |
| send(data) | fn | 发送文本消息,成功返回 true |
| write(data) | fn | 等同于 send(data) |
| close() | fn | 关闭连接,返回 true |
ws = net.connect({ type:'ws', url:'ws://127.0.0.1:8081/ws' }) count = 0 ws.on_message(fn(data){ println('收到服务器消息:' + data) count = count + 1 if count >= 2 { ws.close() } }) ws.on_close(fn(){ println('连接已关闭') }) ws.on_error(fn(err){ println(err) }) ws.send('hello')
客户端对象支持:
| 字段/方法 | 类型 | 说明 |
|---|---|---|
| addr | string | 连接 URL |
| type | string | 固定为 ws |
| send(data) | fn | 发送文本消息,成功返回 true |
| write(data) | fn | 等同于 send(data) |
| close() | fn | 关闭连接,返回 true |
| on_message(fn) | fn | 注册消息回调,回调参数为 data |
| on_close(fn) | fn | 注册关闭回调,无参数 |
| on_error(fn) | fn | 注册错误回调,回调参数为 err |
浏览器或 WebView 页面也可以连接到 BT WebSocket 服务:
const ws = new WebSocket('ws://127.0.0.1:8081/ws') ws.onmessage = event => console.log(event.data) ws.onopen = () => ws.send('hello')
route 指定路径,路径不匹配会返回 404。
socket.send() 内部使用有界队列,队列满时会返回错误。
ws:// 明文连接。
on_message。
socket.read() 方法,接收消息必须使用 on_message。