// 是否在开发模式下运行此服务器(y/n) 输入y ? Do you want to run this server in development mode? (y/N) // 设置服务器的端口 默认 6001 输入 6001就可以了 或者你想要的 ? Which port would you like to serve from? (6001) // 想用的数据库 选择 redis ? Which database would you like to use to store presence channel members? (Use arrow keys) ❯ redis sqlite // 这里输入 你的laravel 项目的访问域名 ? Enter the host of your Laravel authentication server. (http://localhost) // 选择 网络协议 http ? Will you be serving on http or https? (Use arrow keys) ❯ http https // 您想为HTTP API生成客户端ID/密钥吗 N ? Do you want to generate a client ID/Key for HTTP API? (y/N) // 要设置对API的跨域访问吗?(y/n)N Configuration file saved. Run laravel-echo-server start to run server.
/** * Create a new event instance. * * @param User $user * @param string $message */ public function __construct(string $message) { $this->message = $message; }
/** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('push'); }
//Laravel 默认会使用事件的类名作为广播名称来广播事件,自定义: public function broadcastAs() { return 'push.message'; }
//想更细粒度地控制广播数据: public function broadcastWith() { return ['message' => $this->message,'status' => 'okok']; }
// laravel-echo-server 1.5 版本的 需要添加 否则Laravel echo channel listen 不监听事件 public function handle() { broadcast(new push()); }
b.添加路由
1 2 3 4 5 6 7 8
use App\Events\PublicMessageEvent; Route::get('/echo', function () { return view('echo'); });
Route::get('/push/{message}', function ($message) { broadcast(new PublicMessageEvent($message)); })
/** * Create a new event instance. * * @param User $user * @param string $message */ public function __construct(User $user, string $message) { $this->user = $user; $this->message = $message; }
/** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('privatePush.' . $this->user->id); }
//想更细粒度地控制广播数据: public function broadcastWith() { return ['message' => $this->message,'status' => 'okok']; }
添加发布广播到私有频道 触发路由 routes/web 测试时记得新增下用户
1 2 3 4 5
Route::get('/privatePush/{message}/{id}', function ($message, $id) { $user = \App\User::find($id); if (empty($user)) return '无此用户'; broadcast(new PrivateMessageEvent($user, $message)); });