这是事件
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class FieldWasUpdated implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $instance;
public $key;
public $value;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($instance, $key, $value)
{
$this->instance = $instance;
$this->key = $key;
$this->value = $value;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new Channel("model." . $this->instance->getModelType() . "." . $this->instance->id);
}
//public function broadcastAs() {
// return "FieldWasUpdated"; commented out for testing
//}
}
这是前端代码
window.Echo = new window.LaravelEcho({
broadcaster: 'socket.io',
host: window.location.hostname + ':3000'
});
// I use different types of `listen` for testing
Echo.channel("model.ANNOUNCEMENT.2")
.listen(".*", function(e) {
console.log(e);
})
.listen("*", function(e) {
console.log(e);
})
.listen("FieldWasUpdated", function(e) {
console.log(e);
})
.listen(".FieldWasUpdated", function(e) {
console.log(e);
})
node.js代码
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
redis.psubscribe('*', function(err, count) {
console.log(err, count);
});
redis.on('pmessage', function(subscribed, channel, message) {
// different types of emit for testing
message = JSON.parse(message);
const ev = channel + ":" + message.event;
io.emit(ev, message.data);
io.emit(channel, message);
io.emit(message, channel);
io.emit(channel, message.event, message.data);
io.emit(channel, message);
io.emit(channel, message.data, message.event);
});
以下是我在laravel app中触发事件时在chrome开发工具中看到的内容
所以websocket正在运行,但没有一个处理程序被调用。
当我取消注释broadcastAs功能时,没有任何改变。
当我在后端和前端将频道重命名为test-channel
时 - 没有任何变化。
答案 0 :(得分:0)
经过一段时间找到解决方案:
服务器:
redis.psubscribe('*', function(err, count) {
console.log(err, count);
});
redis.on('pmessage', function(subscribed, channel, message) {
message = JSON.parse(message);
io.emit(message.event, channel, message.data);
});
客户端
// both handlers process same event
Echo.channel("model.ANNOUNCEMENT.2")
.listen("FieldWasUpdated", function(e) {
console.log(e);
})
.listen(".App.Events.FieldWasUpdated", function(e) {
console.log(e);
})