Laravel Echo SocketIO拥有私人频道

时间:2017-05-10 16:54:21

标签: laravel sockets laravel-5 socket.io laravel-echo

大家好我和Laravel Echo和SocketIO一起工作而没有Vue只有jquery,但我在这里有私人频道的问题我告诉你我有两个正常的频道和私人频道正常频道(我的事件HolaEvent的todocanales)工作正常当我在这个活动中吃午饭时

use App\Events\HolaEvent;

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

    $data = [
        'type'    => 'erhelloror',
        'title'   => 'new article has been published',
        'message' => 'check it out',
        'url'     => 'url',
    ];
    event(new HolaEvent($data));
    return 'done';
});

在我的laravel echo服务器控制台中显示:

[03:04:47] - 5s6214Rlv51NUgnDAAAA joined channel: todocanales
[03:04:48] - QpxGvCjmaezgHn3aAAAB authenticated for: private-like-received.2jzwpAg1
[03:04:48] - QpxGvCjmaezgHn3aAAAB joined channel: private-like-received.2jzwpAg1
Channel: todocanales
Event: App\Events\HolaEvent
CHANNEL todocanales

在浏览器控制台中,我得到了

~~~ 对象{data:Object,socket:null} ~~~

所有完美,但与privateChannel我有问题Laravel Echo服务器没有做任何事情,我的用户控制台上没有任何记录,当然,我已经运行

php artisan queue:listen redis

我的私人频道我在我的控制器中为活动提供午餐

use App\Events\NewLikePostEvent;

$data = array(
     'user_id' => Hashids::encode($post->user_id),
     'user_name' => $name_user
);

event(new NewLikePostEvent($data));

在项目中我有这个文件:

channels.php

Broadcast::channel('like-received.{id}', function ($user, $id) {
    return true;
});

Broadcast::channel('todocanales', function ($user, $id) {
    return true;
});

bootstrap.js

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://imagenes.dev:6001'
});

app.js

$(document).ready(function(){

    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'X-Socket-Id': Echo.socketId()
            }
    });

    var receiverId = document.getElementById('receiver_id').value;


    Echo.private('like-received.'+ receiverId).listen('NewLikePostEvent', function(e) {
        console.log("Wena!, a "+e.data.user_name + " le ha gustado uno de tus aportes");
        console.log(e);
    });


    Echo.channel('todocanales').listen('HolaEvent', function(e) {
        console.log(e);
    });

});

对于receiverId我使用隐藏在页脚中的输入

<input type="hidden" id="receiver_id" value="{{Hashids::encode(Auth::user()->id)}}" />

我有两个事件

NewLikePostEvent.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
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 NewLikePostEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $data;

    public function __construct(array $data = [])
    {
        $this->data = $data;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('like-received.'.$this->data->user_id);

    }
}

HolaEvent.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
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 HolaEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $data;

    public function __construct(array $data = [])
    {
        $this->data = $data;
    }

    public function broadcastOn()
    {
        return new Channel('todocanales');

    }
}

我的laravel-echo-server.json

{
    "authHost": "http://imagenes.dev",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "ec69415ae1adcbf2",
            "key": "578712cd13fd83f7cadef22742d6728c"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "host": "127.0.0.1",
            "port": "6379"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "imagenes.dev",
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": ""
}

.env文件(不是最重要的部分)

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:ewoyjfyNjXd0FArdsfdsfsNLV7VQH35s=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://imagenes.dev
SOCKET_PORT=6001

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=imagenes
DB_USERNAME=root
DB_PASSWORD=secret

BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

我已经使用node server.js

运行此套接字io脚本

server.js

require('dotenv').config();
const server = require('http').Server();
const io = require('socket.io')(server);
const Redis = require('ioredis');
const redis = new Redis();

server.listen({
    port: process.env.SOCKET_PORT
});

redis.subscribe('*');

console.log(process.env.SOCKET_PORT);


redis.on('like-received.*', function (channel, message) {
    const event = JSON.parse(message);
    io.emit(event.event, channel, event.data);
});

redis.on('todocanales', function (channel, message) {
    const event = JSON.parse(message);
    io.emit(event.event, channel, event.data);
});

最后是我的

BroadcastServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        Broadcast::routes(['middleware' => ['web', 'auth']]);

        require base_path('routes/channels.php');
    }
}

当在队列的控制台中执行具有私有通道的事件Ne​​wLikePostEvent时无限获取

控制台输出

?[33m[2017-05-10 07:07:10] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:12] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:14] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:16] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:18] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:20] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:21] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:23] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:25] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:27] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:29] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:31] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:33] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:35] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:37] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:38] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:40] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:42] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:44] Processing:?[39m App\Events\NewLikePostEvent
?[33m[2017-05-10 07:07:46] Processing:?[39m App\Events\NewLikePostEvent

PS:我知道在服务器中使用maxTries只是对我案例的无限循环事件的更多信息

我把代码放在一边,因为未来可能有所帮助我希望有人可以帮助我:D

问候!

2 个答案:

答案 0 :(得分:2)

如果没有完整的源代码和正在运行的应用,这个问题很难解决。

所以你有私人频道的问题。

我已经在这个聊天应用中实现了所有3种类型的频道(私人,公共和在线),也许你可以从中获得一些想法:

https://github.com/xparthx/laravel-realtime-chat

由于

答案 1 :(得分:1)

固定!

事件是无限处理并且从未被处理的问题是因为在我的事件中我使用:

public function broadcastOn()
{
    return new PrivateChannel('like-received.'.$this->data->user_id);

}

但是$ data是一个数组而不是对象它是我的输入错误xD和通道的名称我替换了点(。)为( - )

'like-received.'.$this->data->user_id

'like-received-'.$this->data['user_id']

最后广播是

public function broadcastOn()
{
    return new PrivateChannel('like-received-'.$this->data['user_id']);

}

以及其他代码我与Parth Vora的代码仓库混合:)(谢谢!)https://github.com/xparthx/laravel-realtime-chat

我不需要使用server.js文件,因此我们使用Laravel echo服务器

和app.js我改为

window.Echo.private('like-received-'+window.Laravel.user).listen('NewLikePostEvent', function(e) {
    console.log("Wena!, a "+e.data.user_name + " le ha gustado uno de tus aportes");
    console.log(e);

});

你可以看到我现在使用了我在刀片文件

上创建的window.Laravel.user
<script>
        window.Laravel = {
            'csrfToken': '{{ csrf_token() }}',
            'user': '{{Hashids::encode(Auth::user()->id)}}'
        };
 </script>

我希望这会对某人有所帮助,因为我尝试了3天来修复这个哈哈哈:D