使用socket.io阻止向多个房间发送消息

时间:2018-01-06 04:49:33

标签: node.js socket.io chat

我使用这个聊天室示例作为参考设置了多房间socket.io / nodeJS聊天服务器:

https://raw.githubusercontent.com/socketio/socket.io/master/examples/chat/index.js

我使用此文档修改从单个房间到多个房间的代码:

https://socket.io/docs/rooms-and-namespaces/

我还修改了代码,在端口8080而不是HTTP上使用HTTPS。

我实施了多个房间。但是,当新用户加入不同的聊天室时,他们的消息将被发送到所有其他聊天室。我想这可能是因为每个人都加入了原来的房间。我的节点控制台日志中的示例:

加入:测试// user1
加入:测试// user2
加入:test2 // user3
user1在测试中说了些什么 user2正在输入测试
user3在测试中说了些什么

客房应通过URL GET参数动态加入,例如?room = room123

这是nodeJS index.js代码。客户端代码与上面的github链接几乎相同。我是node和JS的新手。关于什么事情发生的任何想法?

// Setup basic express server
var express = require('express');
var app     = express();
var path    = require('path');
var fs      = require('fs');
var https   = require('https');
var url     = require('url');

var privateKey  = fs.readFileSync('/etc/letsencrypt/live/hostname/privkey.pem', 'utf8');
var certificate = fs.readFileSync('/etc/letsencrypt/live/hostname/fullchain.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var server = https.createServer(credentials, app);


var io = require('socket.io')(server);
var port = process.env.PORT || 8080;

/* CONSOLE COLORS */
var GREEN  = '\033[0;32m';
var LBLUE  = '\033[1;34m';
var BLUE   = '\033[0;34m';
var RED    = '\033[0;31m';
var YELLOW = '\033[0;33m';
var PURPLE = '\033[0;35m';
var NC     = '\033[0m'; // No Color Reset

/* Chatroom Settings */
var numUsers = 0;
var roomID = null;


server.listen(port, function () {
  console.log('HTTPS Server listening on port ' + GREEN + '%d' + NC, port);
});

/* Routing */
app.use(express.static(path.join(__dirname, 'public')));


chat();



function chat(){

  // multiple rooms
  io.on('connection', function(socket){
    var addedUser = false;
    var referer = url.parse(socket.handshake.headers.referer);
    var query = (referer.query).split("=");
    roomID = query[1];
    socket.join(roomID);


/* // attempt to resolve issue of sending messages to all rooms
console.log(socket.adapter.sids);
    if(Object.keys(socket.adapter.sids).length < 1){
      console.log('Connecting to room:' + roomID);
      socket.join(roomID);
    }
*/

    console.log("Joining: " + YELLOW + roomID + NC);
    //console.log("UUID: " + Object.keys(socket.adapter.nsp.connected)[0]);
    //console.log("unique room id:" + Object.keys(socket.adapter.sids));


    // when the client emits 'new message', this listens and executes
    socket.on('new message', function (data) {
      // we tell the client to execute 'new message'
      socket.to(roomID).emit('new message', {
        username: socket.username,
        message: data
      });

      console.log(socket.username + ' said something in \t' + YELLOW + roomID + NC);
    });

    // when the client emits 'add user', this listens and executes
    socket.on('add user', function (username) {
      if (addedUser) return;
      // we store the username in the socket session for this client
      socket.username = username;
      ++numUsers;
      addedUser = true;
      socket.emit('login', {
        numUsers: numUsers,
    });

      // echo to room that a person has connected
      socket.to(roomID).emit('user joined', {
        username: socket.username,
        numUsers: numUsers
      });

    });

    // when the client emits 'typing', we broadcast it to others
    socket.on('typing', function () {
      console.log(socket.username + ' is typing in \t' + YELLOW + roomID + NC);
      socket.to(roomID).emit('typing', {
        username: socket.username
      });
    });

    // when the client emits 'stop typing', we broadcast it to others
    socket.on('stop typing', function () {
      socket.to(roomID).emit('stop typing', {
        username: socket.username
      });
    });

      // when the user disconnects.. perform this
      socket.on('disconnect', function () {
        console.log(socket.username + PURPLE + ' disconnected' + NC
                                    + ' from ' + YELLOW + roomID + NC);
        if (addedUser) {
          --numUsers;
          // echo that this client has left
          socket.to(roomID).emit('user left', {
            username: socket.username,
            numUsers: numUsers
          });
        }
      });

    });

}

2 个答案:

答案 0 :(得分:1)

我在代码中看到所有套接字都使用相同的roomID变量。他们每个人都需要拥有自己的roomID变量。

答案 1 :(得分:0)

该问题最终由全局“var roomID”变量引起。一旦我在所有socket.to(query [1])中使用了查询[1]变量。发出它起作用的函数。