前言
在很多现代 Web 应用中,WebSockets被用于实现实时更新的用户接口。当一些数据在服务器上
被更新,通常一条消息通过 Websocket 连接被发送给客户端处理。这为我们提供了一个更强大的、更有效的选择来持续拉取应用的更新。
为实现的这样的应用,Laravel 中 通过 Websocket 连接广播事件使开发变得简单。广播 Laravel 事件允许你在服务端和客户端 JavaScript 框架之间共享同一事件名
本 文档 仅使用了 redis的广播驱动
简介
laravel 的广播系统和队列系统类似,需要两个进程协作,一个是 laravel 的 web 后台系统,另一个是 Socket.IO 服务器系统。具体的流程是页面加载时,网页 js 程序 Laravel Echo 与 Socket.IO 服务器建立连接, laravel 发起通过驱动发布广播,Socket.IO 服务器接受广播内容,对连接的客户端网页推送信息,以达到网页实时更新的目的。
配置
配置文件 config/broadcasting.php,可以直接在 .env 中配置以下代码
代码语言:php
复制
BROADCAST_DRIVER=redis
广播服务提供者
代码语言:php
复制
config/app.php 配置文件中 providers数组中打开注释
App\Providers\BroadcastServiceProvider::class,</code></pre></div></div><h5 id="3nf0s" name="CSRF%E4%BB%A4%E7%89%8C">CSRF令牌</h5><p>Laravel Echo需要访问当前 Session 的 CSRF 令牌(token)</p><p>自创建的 blade视图的 head中 加入 meta标签</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> <meta name="csrf-token" content="{{ csrf_token() }}"></code></pre></div></div><h5 id="fuieg" name="Redis">Redis</h5><p>Redis广播需要安装 Predis库</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> composer require predis/predis</code></pre></div></div><h5 id="amr96" name="%E5%AE%89%E8%A3%85Laravel-Echo">安装Laravel Echo</h5><p>Laravel Echo是一个JavaScript库,web端可以轻松订阅频道并收听Laravel广播的事件</p><p>通过 npm 包管理器安装 Echo</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>node</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-node"><code class="language-node" style="margin-left:0"> npm install
npm install laravel-echo-server
初始化 laravel-echo-server
laravel-echo-server init
// 是否在开发模式下运行此服务器(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.</code></pre></div></div><p>设置完成后 项目根目录 下 会生成 laravel-echo-server.json 文件 这里面就是刚才的配置</p><p>执行命令启动 服务 出现如下 则启动成功</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>node</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-node"><code class="language-node" style="margin-left:0"> laravel-echo-server start
L A R A V E L E C H O S E R V E R
version 1.4.2
⚠ Starting server in DEV mode...
✔ Running at localhost on port 6001
✔ Channels are ready.
✔ Listening for http events...
✔ Listening for redis events...
Server ready!</code></pre></div></div><h3 id="atmp0" name="%E9%A2%91%E9%81%93">频道</h3><p>频道必须是 Channel、PrivateChannel 或 PresenceChannel 的实例。Channel 实例表示任何用户都可以订阅的公开频道,而 PrivateChannels 和 PresenceChannels 则表示需要 频道授权 的私有频道:</p><h5 id="4bthp" name="%E5%88%9B%E5%BB%BA%E4%BA%8B%E4%BB%B6">创建事件</h5><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>shell</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-shell"><code class="language-shell" style="margin-left:0"> php artisan make:event PublicMessageEvent </code></pre></div></div><p>文件生成目录 app/Events</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> // 消息内容
public $message;
public function __construct(string $message)
{
$this->message = $message;
}
// 返回一个公共频道 频道名称为push
public function broadcastOn()
{
return new Channel('push');
}
// Laravel 默认会使用事件的类名作为广播名称来广播事件,自定义:
public function broadcastAs()
{
return 'push.message';
}</code></pre></div></div><p> 添加路由</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> use App\Events\PublicMessageEvent;
Route::get('/echo', function () {
return view('echo');
});
Route::get('/push/{message}', function ($message) {
broadcast(new PublicMessageEvent($message));
})</code></pre></div></div><h4 id="3qtg6" name="%E5%89%8D%E7%AB%AF">前端</h4><p>安装 laravel-echo</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>shell</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-shell"><code class="language-shell" style="margin-left:0"> npm install laravel-echo</code></pre></div></div><p>编辑 resource/js/bootstrap.js 添加如下代码</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>js</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-js"><code class="language-js" style="margin-left:0"> import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});</code></pre></div></div><p>编辑 resource/js/app.js 添加如下代码</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>js</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-js"><code class="language-js" style="margin-left:0"> Echo.channel('push')
.listen('.push.message', (e) => {
alert('来了')
console.log(e);
});</code></pre></div></div><p>创建 echo.blade.php</p><p>head 中加上</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> <meta name="csrf-token" content="{{ csrf_token() }}">
<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="/js/app.js"></script></code></pre></div></div><p>编译 js 文件</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>shell</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-shell"><code class="language-shell" style="margin-left:0"> npm run watch</code></pre></div></div><p>浏览器访问 项目域名/echo</p><p>浏览器访问 项目域名/push/这是一个测试广播</p><p>echo 页面 会自动弹出 </p><p>到这 广播 发布到公共频道就完成了</p><h3 id="61i3g" name="%E7%A7%81%E6%9C%89%E9%A2%91%E9%81%93-PrivateChannel">私有频道 PrivateChannel</h3><h5 id="9o4oa" name="%E5%88%9B%E5%BB%BA%E4%BA%8B%E4%BB%B6">创建事件</h5><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>shell</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-shell"><code class="language-shell" style="margin-left:0"> php artisan make:event PrivateMessageEvent</code></pre></div></div><p>PrivateMessageEvent 中 写入 以下内容</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> class PrivateMessageEvent implements ShouldBroadcast
{
// 消息内容
public $message;
// 用户
public $user;
public function __construct(User $user, string $message)
{
$this->user = $user;
$this->message = $message;
}
// 创建私有频道
public function broadcastOn()
{
return new PrivateChannel('privatePush.' . $this->user->id);
}
// //Laravel 默认会使用事件的类名作为广播名称来广播事件,自定义:
// public function broadcastAs()
// {
// return 'privatePush.message';
// }
// 控制广播数据:
public function broadcastWith()
{
return ['message' => $this->message,'status' => 'okok'];
}
}</code></pre></div></div><h5 id="3af3" name="%E6%B7%BB%E5%8A%A0%E5%8F%91%E5%B8%83%E5%B9%BF%E6%92%AD%E5%88%B0%E7%A7%81%E6%9C%89%E9%A2%91%E9%81%93-%E8%A7%A6%E5%8F%91%E8%B7%AF%E7%94%B1-routes/web">添加发布广播到私有频道 触发路由 routes/web</h5><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> Route::get('/privatePush/{message}/{id}', function ($message, $id) {
$user = \App\User::find($id);
if (empty($user)) return '无此用户';
broadcast(new PrivateMessageEvent($user, $message));
});</code></pre></div></div><h5 id="fdg87" name="%E9%A2%91%E9%81%93%E6%8E%88%E6%9D%83">频道授权</h5><p>定义授权路由 routes/channel 中加入一下代码</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> Broadcast::channel('privatePush.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});</code></pre></div></div><h5 id="8gi42" name="%E5%89%8D%E7%AB%AF">前端</h5><p>echo.blade.php 中加入</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> <script>
@if(!empty(Auth::user()))
window.id = "{{Auth::user()->id}}"
@endif
</script></code></pre></div></div><p>app.js </p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>php</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-php"><code class="language-php" style="margin-left:0"> Echo.private('privatePush.' + window.id)
.listen('PrivateMessageEvent', (e) => {
alert('qweqwe')
console.log(e);
});</code></pre></div></div>