配套视频地址:https://www.bilibili.com/video/av78577184?p=2
配置
取消注释 BroadcastServiceProvider,用来注册广播授权路由和闭包。 // config/app.php
配置驱动 "pusher", "redis", "log", "null" // .env
配置数据库
npm install --save socket.io-client // websocket 客户端
npm install --save laravel-echo // websocket 客户端封装
npm install -g laravel-echo-server // websocket 服务端
npm install // 安装所有依赖
npm run watch // 监控文件变化编译前端资源
laravel-echo-server init // 初始化 websocket 服务端
laravel-echo-server start // 启动 websocket 服务端
初始化 websocket 客户端
// bootstrap.js
import Echo from "laravel-echo"
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
事件
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class Prize implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $msg;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($msg)
{
$this->msg = $msg;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('three_good');
}
}
设置频道权限
Broadcast::channel('three_good', function ($user) {
// $ids = \DB::table('three_goods')->pluck('user_id')->toArray();
$ids = [2, 3, 4, 8];
return in_array($user->id, $ids);
});
设置客户端监听广播
window.Echo.private('three_good')
.listen('Prize', (e) => {
console.log(e);
});
触发事件的路由
Route::get('/event', function () {
event(new \App\Events\Prize('到教导处来领取奖状'));
});
引入 js 到前端
<!doctype html>
<html lang="en">
<head>
<title>Laravel</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/js/app.js"></script>
</head>
<body>
<button onclick="axios.get('/event')">send</button>
</body>
</html>
只对其他人广播
Route::get('/event', function () {
broadcast(new \App\Events\Prize('到教导处来领取奖状'))->toOthers();
});
2条评论
cyyyrcyx
完全按照视频中的步骤,公有频道能在Console中收到信息,但私有频道无论如何在Console中都收不到信息,不知是什么原因。
helloWorld
跟着视频多来几次就可以找到问题。