first commit
This commit is contained in:
92
socketEnd/utils/WebSocket.js
Normal file
92
socketEnd/utils/WebSocket.js
Normal file
@@ -0,0 +1,92 @@
|
||||
const Socket = require("ws");
|
||||
const utils = require("./utils");
|
||||
|
||||
class WebSocket {
|
||||
constructor(options) {
|
||||
this.SocketList = {};
|
||||
this.options = {};
|
||||
this.WS = null;
|
||||
|
||||
this.options = options;
|
||||
|
||||
this.createServer()
|
||||
}
|
||||
|
||||
|
||||
createServer() {
|
||||
const WS = new Socket.Server(this.options);
|
||||
WS.on('connection', (ws, req) => this.connection(ws, req))
|
||||
}
|
||||
|
||||
async connection(ws, req) {
|
||||
console.log('建立连接:', req.url);
|
||||
const id = req.url.split('/')[1];
|
||||
if (!id) return ws.close();
|
||||
|
||||
this.SocketList[id] = ws;
|
||||
ws.id = id;
|
||||
this.filter();
|
||||
|
||||
ws.on('message', this.message.bind(this));
|
||||
ws.on('close', (msg) => this.close(msg, ws.id));
|
||||
}
|
||||
|
||||
async message(msg) {
|
||||
msg = msg.toString('utf-8');
|
||||
try {
|
||||
const message = JSON.parse(msg);
|
||||
switch (message.type) {
|
||||
// 收到客户端1 android 的消息
|
||||
// 需要 拿到到GPS的经纬度 进行距离判断
|
||||
// 然后服务器 向客户端2 推送消息
|
||||
case 1:
|
||||
|
||||
console.log("收到客户端1 android 的消息");
|
||||
this.sendMessage({ data: "start" }, "clent2")
|
||||
break;
|
||||
|
||||
// 收到客户端2的消息
|
||||
case 2:
|
||||
// this.send("flutter客户端2测试")
|
||||
console.log("收到客户端2的消息", message);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
console.log("消息格式必须为Object");
|
||||
}
|
||||
}
|
||||
|
||||
async filter() {
|
||||
for(let key in this.SocketList) {
|
||||
if (!this.SocketList[key].readyState === 1) delete this.SocketList[key]
|
||||
}
|
||||
}
|
||||
|
||||
close(msg, id) {
|
||||
console.log('关闭连接', id, msg);
|
||||
}
|
||||
|
||||
sendMessage(msg, id) {
|
||||
// console.log("==================");
|
||||
if(id) {
|
||||
// console.log("if ==== ", msg, id);
|
||||
// console.log("this.SocketList ==== : ", this.SocketList);
|
||||
if (this.SocketList[id].readyState === 1) {
|
||||
this.SocketList[id].send(JSON.stringify(msg));
|
||||
}
|
||||
} else {
|
||||
// console.log("else");
|
||||
// console.log("this.SocketList: ", this.SocketList);
|
||||
for (let ws of Object.values(this.SocketList)) {
|
||||
if (ws.readyState === 1) ws.send(JSON.stringify(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = WebSocket;
|
||||
Reference in New Issue
Block a user