我尝试使用 laravel-echo 服务器和 socket.io 创建实时应用程序,但客户端没有变成消息
这是我的代码:
.env
BROADCAST_DRIVER=redis
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=redis
配置/队列.php
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
],
配置/数据库.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');
}
}
消息控制器.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 请求