【问题标题】:How to connect a user to sockets如何将用户连接到套接字
【发布时间】:2013-08-29 06:08:19
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2018-07-21
      • 1970-01-01
      相关资源
      最近更新 更多