使用laravel,Socket和Redis更改通道动态

时间:2018-04-17 20:20:43

标签: laravel-5 redis socket.io vuejs2

!!!         服务器 - 套接字如何改变通道动态

例如,当我使用/ fire / 1广播时,我只想发送到/ room / 1.

目前它发送到/ room / 1,/ room / 2,/ room / 3等。因为默认情况下,服务器上的所有内容都订阅了“test-channel”。我只是想不出来。

var server = require('http').Server();

var io = require('socket.io')(server);

var Redis = require('ioredis');
var redis = new Redis();


io.on('connection', function(socket){
    console.log('New User Conected here');

 redis.subscribe('test-channel');

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

    socket.emit(channel + ':' + message.event, message.data);
});

socket.on('joinRoom', function(room ){

    console.log('Join in  this Room '+ room);
    socket.join(room);

    });

});
server.listen(3000);

    event | php


    public function broadcastOn()
    {

         return ['test-channel']; // static

    }

1 个答案:

答案 0 :(得分:0)

向广播事件添加属性,然后将其传递给构造函数。

class Message implements ShouldBroadcast{
    use SerializesModels;

    protected $channel;

    public function __construct($channel){
        $this->channel = $channel;
    }

    public function broadcastOn(){
       return [$this->channel];
    }
}

然后,当您触发事件时,请通过以下频道:event(new Message($channel));