1

我正在尝试连接使用登录后为每个用户创建的 cookie 创建的用户会话 ID,并将其连接到套接字......任何方向或示例都会很棒......我正在使用 nodejs、express、redis、socket。 io 并将 mongodb 用于我的数据库的其余部分。

这是 app.js 文件中的代码(但我不确定其中一些)

var connect = require('connect');
var RedisStore = require('connect-redis')(express);
  var redis = require("redis").createClient();
  var io = require('socket.io');
  var notificationsN = io.listen(server);

app.use(express.session({
      secret: "secret sauce",
      store: new RedisStore({ host: 'localhost', port: 3000, client: redis })
  }));

//Not sure if below is correct actually... need to connect it with the current user... how do i go about doing that?

notificationsN.on('connection', function(client) {
    const subscribe = redis
    subscribe.subscribe('realtime');

    subscribe.on('message', function(channel, message) {
      client.send(message);
      console.log('message received from ' + channel + " : " + message);
    });

    client.on('message', function(msg) {
      console.log(msg);
    });

    client.on('disconnect', function() {
      console.log('disconnecting from redis');
      subscribe.quit();
    });

  });

这是客户端:

script(src='http://localhost:3000/socket.io/socket.io.js')
script.
            var socket = io.connect('http://localhost/3000/');

            socket.on('connect', function (data) {
                setStatus('connected');
                socket.emit('subscribe', { channel: 'realtime' });
            });

            socket.on('reconnecting', function(data) {
                setStatus('reconnecting');
            });

            socket.on('message', function(data) {
                console.log('received a message: ', data);
                addMessage(data);
            });

            function addMessage(data) {
                $('#notificationNumber').html(data);
            }

            function setStatus(msg) {
                console.log('connection status: ' + msg);
            }
4

1 回答 1

1

如果我正确理解您的问题,这应该是您的解决方案:http ://www.danielbaulig.de/socket-ioexpress/

于 2013-09-03T09:07:09.777 回答