2022-07-29 16:07:09 +08:00

98 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
TODO:
* 在指定的房间内广播数据 BroadcastInRoom(roomid, msg)
* 探索出能解决将同一roomid的客户加入房间的问题的方法
FIXME:
* 暂无待修正
XXX:
* 房间功能
*/
// 导入模块
var WebsocketServer = require('websocket').server;
var http = require('http');
//const { client } = require('websocket');
// 创建http服务器用于承载WS
var server = http.createServer();
// 端口设置端口
const PORT = 3000 || process.env.PORT
// 客户端列表
clientsList = [];
// http绑定端口
server.listen(PORT, () => {
console.log("Server running on http://localhost:" + PORT);
});
// 在http服务器上运行WS服务器
var wsServer = new WebsocketServer({httpServer:server});
// 当客户端连入时
wsServer.on('request', (websocketRequest) => {
var connection = websocketRequest.accept(null, 'accepted-origin');
//将客户端插入终端列表
clientsList.push(connection);
console.log('A client connected');
// 当收到消息时
connection.on('message', (msg) => {
// 判断消息类型
if(msg.type == 'utf8'){
// 过滤非法数据
try {
/*
定义的数据传送格式规范JSON
tag数据标签
msg数据内容
optBoolean确认是否为执行操作操作tag与用户传输的tag重合。
args: opt参数
*/
// 解析数据
cd = JSON.parse(msg.utf8Data);
// 开发中,将客户端加入某个房间
if(cd.tag == 'setRoom' && cd.opt == true){
// 如果客户端对象没有设置过roomid属性则增设
if(connection.roomid == undefined){
connection.roomid = [];
}
// 将传进来的roomid属性写入
connection.roomid.push(cd.msg);
console.log("Set! roomid = " + connection.roomid);
}
if(cd.tag == 'roomcast' && cd.opt == true && cd.arg != undefined){
console.log('Cast!')
BroadcastInRoom(cd.arg.roomid, 'cast', cd.msg);
}else if(cd.opt == true && cd.arg == undefined){
console.log('Cannot GET arg');
}else{
console.log('Unknown ERROR');
}
console.log(cd);
} catch (error) {
console.log(error);
console.error('Illegal Data');
}
}else{
console.log(msg);
}
});
connection.on('close', (reasonCode, description) => {
console.log('A client disconnected');
});
})
// 房间内消息广播
function BroadcastInRoom(roomid, tag, msg){
for(var i = 0; i < clientsList.length; i++){
if(clientsList[i].roomid == roomid){
clientsList[i].send(JSON.stringify({'tag': tag, 'msg': msg}));
}
}
}