【问题标题】:How do I close a sockjs connection on the server side?如何在服务器端关闭 sockjs 连接?
【发布时间】:2014-09-14 12:27:46
【问题描述】:

所以,每次我刷新页面时,sockjs 似乎都在创建一个新连接。

我在每个 channel.onmessage 上将每条消息保存到我的 mongodb,所以如果我刷新页面 7 次并发送一条消息,我会将相同内容的 7 条消息保存到我的 mongodb 中。

这是非常有问题的,因为当我进入聊天室时检索这些消息时,查看日志时,我会看到一堆重复的消息。

我想跟踪所有“活动”的连接,如果用户尝试建立另一个连接,我希望能够从服务器端强制关闭旧连接,因此只有 1 个连接一次收听每条消息

我该怎么做?

var connections = {};

//creating the sockjs server
var chat = sockjs.createServer();

//installing handlers for sockjs server instance, with the same url as client
chat.installHandlers(server, {prefix:'/chat/private'});

var multiplexer = new multiplexServer.MultiplexServer(chat);

var configChannel = function (channelId, userId, userName){
  var channel = multiplexer.registerChannel(channelId);

  channel.on('connection', function (conn) {
    // console.log('connection');
    console.log(connections);
    connections[channelId] = connections[channelId] || {};

    if (connections[channelId][userId]) {
      //want to close the extra connection
    } else {
      connections[channelId][userId] = conn;
    }

    // }


    // if (channels[channelId][userId]) {
    //   conn = channels[channelId][userId];
    // } else {
    //   channels[channelId][userId] = conn;
    // }

    // console.log('accessing channel! ', channels[channelId]);

    conn.on('new user', function (data, message) {
      console.log('new user! ', data, message);
    });

    // var number = connections.length;

    conn.on('data', function(message) {
      var messageObj = JSON.parse(message);
      handler.saveMessage(messageObj.channelId, messageObj.user, messageObj.message);
      console.log('received the message, ', messageObj.message);
      conn.write(JSON.stringify({channelId: messageObj.channelId, user: messageObj.user, message: messageObj.message }));
    });
    conn.on('close', function() {
      conn.write(userName + ' has disconnected');
    });
  });
  return channel;
};

【问题讨论】:

    标签: javascript node.js websocket chat sockjs


    【解决方案1】:

    只需使用.close:

    if (connections[channelId][userId]) {
      // want to close the extra connection
      connections[channelId][userId].close();
    } else {
      connections[channelId][userId] = conn;
    }
    

    【讨论】:

    • 这是我尝试的第一件事。没用。我重构了 socket.io,所以我可以使用他们的事件系统
    • 所以你修改了Sock.js的代码?无论如何,你得到什么错误?你试过.disconnect吗?您应该检查连接对象的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2019-01-22
    • 2015-01-15
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    相关资源
    最近更新 更多