search

Home  >  Q&A  >  body text

node.js - laravel5.2 broadcaster无法广播,且不报错?

环境:Mac ,laravel版本 5.2.x ,valet

问题描述:

在用laravel配合nodeJS的socket.io做websocket时出现的错误。

这是socket的服务端代码

var http = require('http').Server();
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();

redis.subscribe('test-channel');

redis.on('message', function (channel, message) {
    console.log(message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

http.listen(3001, function () {
   console.log('Server is running at 3001!');
});

这是route代码

Route::get('/test', function () {

    $data = [
        'event' => 'inbox',
        'data' => [
            'name' => 'WTF'
        ]
    ];

    Redis::publish('test-channel', json_encode($data));

    return 'Done';
});

然后访问/test页面后,命令行显示如图:

前端也收到了数据,就不展示了,问题的关键在于

当我将route的代码改成如下:

Route::get('/test', function () {

    event(new \App\Events\Test('ARE U OK ?'));

    return 'Done';
});

然后通过

php artisan make:event Test

生成的event事件代码如下:

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Test extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function broadcastOn()
    {
        return ['test-channel'];
    }
}

然后访问/test页面,命令行无输出

在这之前,是配置过broadcast的driver的

.env文件里

BROADCAST_DRIVER=redis

config的cache也已经clear过了

从使用Redis::publish成功可以看出,laravel和Redis链接是成功的,那么问题应该出在哪里呢?

还请大神指教!

天蓬老师天蓬老师2862 days ago696

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 14:50:22

    After restarting the project, copying the same code, and executing it normally, I found that the problem was caused by the QUEUE_DRIVER=redis of the original project, and it should be a queue problem.

    Change QUEUE_DRIVER=redis to sync.

    reply
    0
  • 阿神

    阿神2017-04-17 14:50:22

    Thank you for the invitation. After roughly looking at the code, it seems that there is no problem. But there is one thing you didn't explain: whether there is a problem with the queue execution.
    Broadcasting event will put the event in a queue for execution. Have you not started queue monitoring?

    First try to change the use IlluminateContractsBroadcastingShouldBroadcast; in your event to the following Now: change it into use IlluminateContractsBroadcastingShouldBroadcastNow; and then test to see if it can be broadcast.

    If possible, remove Now and change it back, then execute php artisan queue:listen on the command line before broadcasting

    reply
    0
  • Cancelreply