发射到单个客户端套接字 io 1.3.2

emitting to single client socket io 1.3.2

我在这里查看了几个答案,但我认为他们指的是 socket.io 的旧版本,因为他们的解决方案对我不起作用。我正在使用

在浏览器中取回数据
io.emit('update', data)

但它会发送给所有客户端,因此当我转到相同的 URL 时,相同的数据会出现在多个 windows 中。我是否必须在连接时将客户端 ID 存储在某处,或者我可以在发出之前取回它?请具体一点。我尝试了其他一些来自 SO 的解决方案,但我得到了很多 ReferenceError 'id' is not defined or sockets instead of socket.

服务器设置和连接:

var app = express();
var server = require('http').createServer(app)
var io = require('socket.io')(server)

app.get('/aPath', function (req, res, next) {
        res.writeHead(200)

    var data = {
        "val1":  req.query.val1,
        "val2":  req.query.val2,
        "val3":  req.query.val3,
        "val4":  req.query.val4,
        "val5":  req.query.val5,
        "val6":  req.query.val6,
    }

    /*console.log(io.sockets.id)*/

    //io.to(io.sockets.id).emit('update', data)
    //io.sockets.socket(id).emit('update', data)
    io.emit('update', data)
    res.end("OK")
})

io.on('connection', function (socket) {
    console.log('websocket user connected')
});

由于 third-party 客户端通过 restful 接口发送信息,您需要以 header 或 header 的形式在该请求中包含客户端的参考数据查询字符串。

我建议使用Redis 来存储活动套接字用户以供快速参考。这将允许您部署多个应用程序,这些应用程序使用单个 redis 实例来保持数据同步。您也可以在应用程序内存中执行相同的操作,但这并不能很好地扩展。

首先,您需要使用中间件对用户进行身份验证并缓存 socket.id

var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('redis');

io.use(function(socket, next){
  // validate user
  // cache user with socket.id
  var userId = validatedUser;
  socket.handshake.userId = userId;
  redis.set(userId, socket.id, function (err, res) {
       next()
  });
});

接下来处理所有套接字通信

io.on('connection', function (socket) {
    console.log('websocket user connected');

    //next handle all socket communication
    socket.on('endpoint', function (payload) {
        //do stuff
        socket.emit('endpoint.response', {/*data*/});
    });

    //Then remove socket.id from cache
    socket.on('disconnect', function (payload) {
        //remove user.id from cache
        redis.del(socket.handshake.userId, function (err, res) {
             console.log('user with %s disconnected', socket.id);
        });
    });
});

处理第三方事件。

app.get('/aPath', function (req, res, next) {
    // get user from third party
    var userId = req.query.userId

    var data = {
        "val1":  req.query.val1,
        "val2":  req.query.val2,
        "val3":  req.query.val3,
        "val4":  req.query.val4,
        "val5":  req.query.val5,
        "val6":  req.query.val6,
    };

    // get cached socketId from userId
    redis.get(userId, function (err, socketId) {
        // return ok to third party;
        res.status(200).send("OK");
        only emit if socketid still exists
        if (err || !socketId) return;
        // now emit to user
        io.to(socketId).emit('update', data):
    });
});