带套接字io和redis的laravel echo服务器

时间:2017-09-07 11:34:12

标签: php laravel redis socket.io laravel-echo

我尝试使用laravel-echo服务器和socket.io创建实时应用程序,但客户端不会成为消息

这是我的代码:

.ENV

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

配置/ queue.php

 'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => 'default',
        'retry_after' => 90,
 ],

配置/ database.php中

'redis' => [

    'retry_after' => 90,
    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

],

路由/ channels.php

Broadcast::channel('messages', function() {
    return true;
}); 

的src / echo.js

import Echo from "laravel-echo"

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

window.Echo.channel('messages')
  .listen('.newMessage', (message) => {
    debugger;
});

活动/ MessagePosted.php

<?php

 namespace App\Events;

 use Illuminate\Broadcasting\Channel;
 use Illuminate\Queue\SerializesModels;
 use Illuminate\Foundation\Events\Dispatchable;
 use Illuminate\Broadcasting\InteractsWithSockets;
 use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessagePosted implements ShouldBroadcast {

 use Dispatchable, InteractsWithSockets, SerializesModels;

protected $message;

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

public function broadcastWith()
{
    return [
        'message' => $this->message,
    ];
}

public function broadcastAs()
{
    return 'newMessage';
}

public function broadcastOn()
{
    return new Channel('messages');
}
}

MessageController.php

public function post(Request $request)
{
    event(new MessagePosted($request->get('message')));
} 

安装Redis服务器,在redis-cli PING命令中返回PONG。 我使用php artisan queue:work redis,但是从客户端发送消息后,没有任何内容显示在队列中...... 客户端连接到laravel-echo-server,返回:        [14:04:17] - C3c8UUnTn9dvOPc9AAAA加入了频道:消息。 并处理POST请求

1 个答案:

答案 0 :(得分:1)

您正在收听.newMessage,但正在发送.App.Events.MessagePosted

更改JS中的listen函数参数:

window.Echo.channel('messages')
  .listen('.App.Events.MessagePosted', (message) => {
  debugger;
});