我得到长度1甚至它没有连接到插座

时间:2016-11-11 04:11:56

标签: node.js socket.io

let app = require('express')(),
    http = require('http').Server(app),
    User = require('../models/users');

http.listen(8080, function () {
    console.log('Socket IO server has been started on port 8080');
});

let io = require('socket.io')(http);
var socketRoom = {};

io.of('/chat').on('connection', function (socket) {
    var ioRooms = io.of('/chat').adapter.rooms;
    console.log(ioRooms) // I got length 1 when I print it.
    socket.on('requestRandomChat', function (data) {
        User.findOne({userToken : data.userToken}, function(err, user){
            if(err) socket.emit('db error');
            if(!user) socket.emit('db error : user not found');
            else {
                socket.emit('responseUserProfile', user);
                for (var key in rooms){
                    if (key == ''){
                        continue;
                    }
                    if (rooms[key].length == 1){
                        var roomKey = key.replace('/', '');
                        socket.join(roomKey);
                        io.sockets.in(roomKey).emit('completeMatch', {});
                        socketRoom[socket.id] = roomKey;
                        return;
                    }
                }
                socket.join(user.userToken);
                socketRoom[user.userToken] = socket.userToken;
            }
        });
    });

    socket.on('cancelRequest', function (data) {
        socket.leave(socketRoom[socket.id]);
        console.log(ioRooms);
    });

    socket.on('sendMessage', function (data) {
        console.log(ioRooms);
        console.log('sendMessage!');
        io.of('/chat').in(socketRoom[socket.id]).emit('receiveMessage', data);
    });

    socket.on('disconnect', function (data) {
        console.log(ioRooms);
        var key = socketRoom[socket.id];
        socket.leave(key);
        io.of('/chat').in(key).emit('disconnect');
        var clients = io.of('/chat').clients(key);
        for (var i = 0; i < clients.length; i++) {
            clients[i].leave(key);
        }
    });
});

当我试图获得一定长度的房间时,我得到一个长度为1的socketId。 但我从来没有连接到房间。那个默认房间?有人可以解释房间插座发生了什么吗?

  

// {'/ chat#2HAMaavywIwZ1B5fAAAD':Room {套接字:{   '/ chat#2HAMaavywIwZ1B5fAAAD':true},length:1}}

1 个答案:

答案 0 :(得分:0)

在套接字io中,每个套接字自动连接到由套接字ID标识的默认空间。

这就是你得到长度1的原因。

我希望你觉得它很有帮助。 http://socket.io/docs/rooms-and-namespaces/