【问题标题】:how to prevent new connection on every page refresh in sockjs如何防止 sockjs 中的每个页面刷新时都有新连接
【发布时间】:2014-07-23 10:50:41
【问题描述】:

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

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

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

我想跟踪所有“活动”连接,如果用户尝试建立另一个连接,我想终止旧连接,这样每次只有一个连接在监听每条消息。

我该怎么做?

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 websocket chat sockjs


【解决方案1】:

我解决像您这样的问题的方法是使用 Closure 和 Promises,我不知道这是否可以帮助您。我让你的代码可以帮助我,这是来自 Vertx 的 EventBus:

window.Events = (function NewEvents() {
  var eventBusUrl = $('#eventBusUrl').val();
  var eventBus = null;

  return new RSVP.Promise(function(resolve, reject) {
    if(!eventBus) {
      eventBus = new vertx.EventBus(eventBusUrl);

      eventBus.onopen = function eventBusOpened() {
        console.log('Event bus online');
        resolve(eventBus);
      }

      eventBus.onclose = function() {
        eventBus = null;
      };
    }
  });
}());

然后在其他脚本中我这样称呼它:

Events.then(function(eventBus) {
  console.log("registering handlers for comments");
  eventBus.registerHandler(address, function(incomingMessage) {
    console.log(incomingMessage);
  });
});

希望对你有帮助。

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2016-01-18
    相关资源
    最近更新 更多