使用socket.io实现多房间通信聊天室

websocket的实现有很多种,像ws和socket.io,这里使用的是socket.io来实现多房间的效果。

这里的使用没有使用socket.io官方提供的namespaceroom,而是完全通过一个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 +='
'+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的操作类型进行同步用户信息,这在实际中很有用。

代码很简单,就是两个类的实现,RoomsUser类,这里没有限定房间的数量,可以在初始化的时候先固定房间名和数量。源码托管于github,地址为:https://github.com/tianxiangbing/rooms ,如果觉得有用,加颗小星星吧

你可能感兴趣的:(websocket,socket.io,聊天室)