向nodejs服务器广播事件

7fyelxc5  于 2021-06-09  发布在  Redis
关注(0)|答案(0)|浏览(277)

我有一个laravelrestapi,我想通过redis(或socket.io)广播事件来扩展它。我在macos上做这件事,redis在6379端口上运行,laravel在vagrant上运行,节点服务器在node server.js上运行;但是,调用事件行时,节点控制台中不会显示任何内容。应用程序的工作方式如下:在返回响应之前,将请求发布到一个最后有事件行的路由->通过redis向node广播事件->node接收事件并发送到channel x。
当我想广播我使用的事件时: event(new BordCreated($bord)); 事件:

<?php

namespace App\Events;

use App\Models\Bord;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class BordCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $bord;

    /**
     * Create a new event instance.
     *
     * @param Bord $bord
     */
    public function __construct(Bord $bord)
    {
        $this->bord = $bord;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('action-channel-one');
    }
}

环境:

BROADCAST_DRIVER=redis
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

节点服务器:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

const SOCKET_PORT = 9000;
const REDIS = {
    "host": "127.0.0.1",
    "port": "6379"
}
var ioRedis = require('ioredis');
var redis = new ioRedis(REDIS);
redis.subscribe('action-channel-one', 'action-channel-two');
redis.on('action-channel-one', function (channel, message) {
    console.log('test2');
})
redis.on('message', function (channel, message) {
    console.log('test');
    message  = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

server.listen(SOCKET_PORT, function () {
    console.log('Socket server is running.');
});

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题