websocket的实现有不少种,像ws和socket.io,这里使用的是socket.io来实现多房间的效果。html
这里的使用没有使用socket.io
官方提供的namespace
和room
,而是彻底经过一个namespace
实现的。数据传输使用JSON
格式,封装了消息规范git
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
把项目从github上clone下来后,执行npm start
,而后打开example/index.html
便可品尝到演示效果github
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端口。web
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
的操做类型进行同步用户信息,这在实际中颇有用。npm
代码很简单,就是两个类的实现,Rooms
和User
类,这里没有限定房间的数量,能够在初始化的时候先固定房间名和数量。源码托管于github,地址为:https://github.com/tianxiangbing/rooms ,若是以为有用,加颗小星星吧websocket