如何在服务器端关闭sockjs连接? [英] How do I close a sockjs connection on the server side?

查看:586
本文介绍了如何在服务器端关闭sockjs连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,每次刷新页面时,sockjs似乎都在创建一个新的连接。

So, every time I refresh the page, it seems like sockjs is creating a new connection.

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

I am saving every message to my mongodb on every channel.onmessage, so if I refresh my page 7 times and send a message, I would save 7 messages of the same content into my mongodb.

这很成问题,因为当我进入聊天室并查看日志时检索这些消息时,会看到一堆重复的消息

This is very problematic because when I retrieve those messages when I go into the chat room, to see the log, I would see bunch of duplicate messages.

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

I want to keep track of all connections that are 'active', and if a user tries to make another connections, I want to be able to force close on the old one from the server side, so there is only 1 connection listening to each message at a time

我该怎么做?

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;
};


推荐答案

只需使用 .close

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

这篇关于如何在服务器端关闭sockjs连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆