construct2-socket.io开房示例

node.js 后台代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 3000;

app.get('/', function (req, res) {
    res.send('<h1>Welcome Realtime Server</h1>');
});

//在线用户
var clients = [];
//当前在线人数
var onlineCount = 0;

http.listen(port, function () {
    console.log('listening on *:3000');
});

io.on('connection', function (socket) {
   
    clients.push(socket);
    console.log('current use number is:======' + clients.length);

   //向所有客户端广播发布的消息
    socket.on('touch', function (obj) {
        //向所有客户端广播发布的消息
        //io.emit('message', obj);
        console.log(obj);
        //发给所有人
        socket.broadcast.emit('touch', obj);
    });
    socket.on('disconnect', function (data) {
        var index = clients.indexOf(socket);
        if (index >= 0) {
            clients.splice(index, 1);
        }
        console.log('current use number is:======' + clients.length);
    })

    ////////
    ////room 
    /////////
    //添加呢称
    socket.on('roomNickName', function (obj) {
        socket.nickname = obj;
        console.log("socketID: " + socket.id + "   nike Name: " + socket.nickname);
    });
    //加入房间
    socket.on('roomjoin', function (obj) {
        if (socket.room != obj) {
            for (var room in socket.rooms) {
                socket.leave(room);
            }
       
        socket.room = obj;
        socket.join(obj);
        console.log("socketID: " + socket.id + "  room is: " + socket.room);
        }
        });


    //列出所有房间名
    socket.on('roomlistroomnames', function () {
        var rooms = io.sockets.adapter.rooms;
        console.log(rooms);
    });

    //删除当前用户
    socket.on('roomleave', function () {
        for (var room in socket.rooms) {
            socket.leave(room);
        }
        console.log(socket.id + "rooms propery is:");
        for (var room in socket.rooms) {
            console.log(room);
        }
    });


    //列出房间所有用户名
    socket.on('roomlistusernames', function () {
       
        var clients = io.sockets.adapter.rooms[socket.room].sockets;
        for (var i1 in clients) {
            console.log(i1);
        }
        

    });


    //房间内发送广播
    socket.on('roombroadcastroom', function (data) {
        //获取房间所有人
        io.sockets.in(socket.room).emit("broadcast",data);

    });
})

猜你喜欢

转载自blog.csdn.net/openbug/article/details/81116569