Socket.io和Redis广播给除发件人以外的所有客户

我在后端使用Laravel来创build一个聊天应用程序。 但是当我使用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']; } } 

你可以用一个额外的参数来扩展emit()函数,比如说send_to_self = True ,如果当前客户端应该被包含,那么这个参数和broadcast = True或者一个房间值一起configuration。 默认情况下将保持不变,但是如果send_to_self设置为False,则循环遍历所有要通知的客户端将跳过当前连接。 要检测哪一个是当前的,你可以使用request.namespace,它是活动客户端的命名空间对象。

所以你的代码是

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

尝试使用通配符

 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); });