How do I close a sockjs connection on the server side?

随声附和 提交于 2019-12-13 02:57:42

问题


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

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.

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

How do I do this ?

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

回答1:


Simply use .close:

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


来源:https://stackoverflow.com/questions/24908482/how-do-i-close-a-sockjs-connection-on-the-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!