【发布时间】:2017-02-26 10:31:13
【问题描述】:
我在后端使用 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