共计 1890 个字符,预计需要花费 5 分钟才能阅读完成。
websocket 的实现有很多种,像 ws 和 socket.io,这里使用的是 socket.io 来实现多房间的效果。
这里的使用没有使用 socket.io
官方提供的 namespace
和room
,而是完全通过一个 namespace
实现的。数据传输使用 JSON
格式,封装了消息规范
消息体规范
const actionType = {
join:'JOIN',// 加入
leave:'LEAVE',// 离开
talk:'TALK',// 消息
action:'ACTION',// 用户操作
push:'PUSH'// 系统推送
}// 消息体
class MSG {constructor(type,body){
this.type = type;
this.body= body;
}}
安装使用
npm install socket.io-rooms --save
demo 演示
把项目从 github 上 clone 下来后,执行 npm start
, 然后打开example/index.html
即可品尝到演示效果
使用方式
服务端 Server
const {User,Rooms} = require('socket.io-rooms')
const server = require('http').createServer();
const io = require('socket.io')(server);
// 大厅
io.on('connection', client => {let user = new User();
client.emit('user',user);
client.on('join', data => {
/\* 加入某个房间 \*/
Rooms.join(data,user,io,client)
});
client.on('message',msg=>{if(user.roomId){// io.to(user.roomId).emit('message',msg)
if(msg.type == 'update'){user.update(msg.body);
}
msg.user = user.uid;
Rooms.send(user.roomId,msg)
}else{io.emit('message',msg)
}
console.log(msg)
})
client.on('disconnect', () => {
/\* … \*/
console.log("连接断开")
Rooms.leave(user)
});
});
server.listen(80);
这里传输统一使用 `JSON` 格式,消息 `title` 也以 `message` 为主, 这里端口写的 80,你可以使用其他端口,如果你是 Express,也可以共用 80 端口。
客户端调用 Client
const socket = io('http://localhost');
log =(...args)=>{document.getElementById('log').innerHTML +='<br/>'+args.map(item=>JSON.stringify(item)).join('')+'=>'+(+new Date());
}
log(socket.id)
let user ={},room,client;
socket.on('connect', (c) => {log('connect ...', socket.id);
socket.on('user',u=>{
user = u;
log('用户 ID',u.uid)
});
});
socket.on('message',msg=>{log('message:',msg)
});
function joinroom(num){
// 加入房间号为 1 的房间
socket.emit('join',num);
}
function send(){let msg = document.getElementById('msg').value;
socket.emit('message',{type:'TALK',body:msg})
// setInterval(function(){// socket.emit('message',{type:'TALK',body:+new Date()})
// },2000)
}
在用户信息上,为了增加扩展性,添加了 update
的操作类型进行同步用户信息,这在实际中很有用。
代码很简单,就是两个类的实现,Rooms
和 User
类,这里没有限定房间的数量,可以在初始化的时候先固定房间名和数量。源码托管于 github,地址为:https://github.com/tianxiangbing/rooms , 如果觉得有用,加颗小星星吧
正文完