Socket.io和Redis向除发送者之外的所有客户端广播

时间:2016-10-17 12:28:42

标签: node.js laravel redis socket.io broadcast

我在后端使用Laravel制作聊天应用。但是当我使用redis时,我无法使用broadcast.send函数。现在如何向除发件人之外的所有客户端发送邮件?此代码有错误:

  

io.broadcast.send(channel +':'+ message.event,message.data);

这是我的所有服务器代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();


redis.subscribe('chat');

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

    // send all client except sender
    io.broadcast.send(channel + ':' + message.event, message.data); 

});


io.sockets.on('connection', function(socket) {      
    console.log('User Connect with ID: ' + socket.id);         
});

// run server
http.listen(3001, function(){
    console.log('Listening on Port 3001');
});

和客户端代码:

var socketClient = io(':3001');
socketClient.on("chat:App\\Events\\ChatEvent", function(message){
        // increase the power everytime we load test route
        console.log(message);       
    });

ChatEvent.php

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ChatEvent extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $message;

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


    public function broadcastOn()
    {
        return ['chat'];
    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用附加参数扩展 emit()函数,例如 send_to_self = True ,以及 broadcast = True 或者如果应包括当前客户端,则将配置房间值。默认情况下,事情将保持不变,但如果send_to_self设置为False,则迭代所有要通知的客户端的循环将跳过当前连接。要检测哪一个是当前的,您可以使用request.namespace,它是活动客户端的名称空间对象。

所以你的代码是

io.emit(channel + ':' + message.event, message.data,send_to_self=false);

答案 1 :(得分:0)

您可以使用辅助广播来执行此操作,然后使用方法toOthers();
更多详细信息,请访问文档https://laravel.com/docs/5.8/broadcasting#only-to-others

答案 2 :(得分:-1)

尝试使用通配符

class messageEvent extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $userid;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($user)
    {

        if($user==\Auth::guard('admin')->user()->id){
                  return false;
         }
        $this->userid = $user;


    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {   
        return ['ChatEvent-'.$this->userid];
    }
}

在Js做出改变

    var socketClient = io(':3001');
    socketClient.on("chat:App\\Events\\ChatEvent-<?php echo \Auth::guard('admin')->user()->id; ?>", function(message){

            console.log(message);       
        });