检查是否有人在Laravel Controller的套接字通道上进行了连接

时间:2019-02-19 17:05:47

标签: sockets websocket socket.io

我有这样的结构:

套接字服务器端:

    var fs = require('fs');
    var pkey = fs.readFileSync('../../../../etc/letsencrypt/privkey.pem');
    var pcert = fs.readFileSync('../../../../etc/letsencrypt/cert.pem')
    var options = {
        key: pkey,
        cert: pcert,
        requestCert: false,
        rejectUnauthorized: false
    };
    var app = require('https').createServer(options);
    var io = require('socket.io')(app);
    var Redis = require('ioredis');
    var redis = new Redis();
    app.listen(8443, function () {
        console.log('Server is running!');
    });

    redis.subscribe('resumo');

    redis.on('message',function(channel,message){
        console.log(channel, message);
        message=JSON.parse(message);

        console.log(channel+':'+message.event, message);
        io.emit()
    });

    function handler(req, res) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.writeHead(200);
        res.end('');
    }

    var totalUsers = 0;

    io.on('connection', function (socket) {
        totalUsers++;
        console.log('a user connected');
        io.emit('users', totalUsers);
        socket.on('disconnect', function(){
            totalUsers--;
            io.emit('users', totalUsers);
            console.log('user disconnected');
        });
        socket.on('exit', function(channel){
            var teste = socket.eventNames();
            console.log('desconectado de: '+teste);
        });
        socket.on('entrar', function(channel){
            socket.join(channel);
            console.log('conectado em: '+channel);
        });
    });
    redis.psubscribe('*', function (err, count) {
        //
    });
    redis.on('pmessage', function (subscribed, channel, message) {
        io.emit(channel, message);
    });

客户端:

    var socket = io.connect('https://mywebsite.com:8443/');
    socket.on('u_123', function (data) {
        data = JSON.parse(data);
        window[data['function']](data);
    });

我在这样的频道上发布:

    Redis::publish('u_123', json_encode([
        'data' => [somedata]
    ]));

我需要检查laravel控制器的此通道'u_123'上是否有人连接,这可能吗?我该怎么办?我在javascript方面真的很不好,所以我在这方面遇到了很多困难...

1 个答案:

答案 0 :(得分:0)

根据socket.IO文档

  

Socket.IO中的每个Socket由一个随机的,不可猜测的唯一标识符Socket#id标识。为方便起见,每个插座会自动加入此ID标识的房间。

因此,您可以在connection事件上将这些ID存储在数组中,并在exit上将其从列表中删除。