如何将用户连接到套接字

时间:2013-08-29 06:08:20

标签: node.js express redis socket.io pug

我正在尝试连接使用为每个用户创建的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);
            }

1 个答案:

答案 0 :(得分:1)

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