# CLGWebSocketServer **Repository Path**: creeve/CLGWebSocketServer ## Basic Information - **Project Name**: CLGWebSocketServer - **Description**: 一个简单的WebSocket服务器,基于node-ws - **Primary Language**: NodeJS - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-07-18 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #CLGWebSocketServer 一个简单的WebSocket服务器,基于node-ws ``` var WebSocketServer = require('ws').Server; // wss = new WebSocketServer({port: 8080}); //新建一个WS服务器 wss.on('connection', function(ws) { // 监听connection事件(终端发起连接时会调用) ws.send('Hello, client'); // 回复客户端消息 ws.on('message', function(message) { // 监听message,回复client发送的message console.log('Msg received in server: %s ', message); ws.send(message); }); }); ``` ## Target 1. 新建一个WS服务器,能接收来自Client的连接。 2. 机顶盒,移动终端都连接上WS服务器 3. 机顶盒提供二维码,移动终端扫码之后,获得机顶盒的信息(能将消息发送给机顶盒的信息) 4. 移动终端发送信息给机顶盒 5. 移动终端监听机顶盒的上下线状态,下线的时候提示机顶盒已经下线 ### Implementation 机顶盒+移动端+服务器 1. 机顶盒获取设备ID,这里以stb_id为例 2. 机顶盒端连接WS服务器:ws://host.com?device_id=xxx,这里host.com是ws服务器地址,xxxx是设备ID 3. 服务器有个全局变量connectedDevice存放当前连接的设备,接受机顶盒的连接请求,解析出device_id,将device_id作为key,对应的WS链接设为value,存放到connectedDevice中。 4. 机顶盒生成一个二维码,包含stb_id信息。 5. 移动端获取设备ID,连接WS服务器,ws://host.com/device_id,和机顶盒类似。 6. 登录成功后,用户扫机顶盒二维码获取对应的stb_id。 7. 后续消息按照`{"from":"device_id", "to":"stb_id", msg:"hello,world"}`进行发送 8. 服务器收到`{"from":"device_id", "to":"stb_id", msg:"hello,world"}`后,在connectedDevice找到stb_id对应的盒子,发送到对应设备。 > 上下线通知:当用户连上服务器时,会全网广播上线信息`{"from":"device_id", "to":"all", msg:"online"}`,下线时,会会全网广播下线信息`{"from":"device_id", "to":"all", msg:"offline"}` > 心跳:设备如果突然断网,WS是无法监听到close消息的,这里需要引入ping心跳,如果心跳无返回,会全网广播下线消息 > 移动端连上服务器时,如何判断当前机顶盒是否在线:可以调用http://host.com/online_status?deviceid=xxx接口,返回数据为: > > ``` > { > "status": 0, > "message": "获取成功在线信息成功", > "data": { > "device_id":"online" > } > } > ``` > > 也可以在登录WS服务器时,添加参数queryStatus=xxx,比如ws://host.com?device_id=xxx&queryStatus=xxx > > 服务器会返回同样的数据 ![]()