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

问题描述 投票:2回答:3

我在后端使用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'];
    }
}
node.js laravel redis socket.io broadcast
3个回答
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);

0
投票

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


-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);       
        });
© www.soinside.com 2019 - 2024. All rights reserved.