文章目录
服务准备
配置驱动
ENV中BROADCAST_DRIVER配置驱动方式 支持以下几种方式
- pusher
- redis
- log
- null
安装客户端
npm install socket.io-client --save //安装sorket 客户端
npm install laravel-echo --save //安装客户端封装
npm install laravel-echo-server -g //安装sorbet 服务端
如果你使用 Redis 广播器,请安装 Predis 库:
composer require predis/predis
初始化服务端
laravel-echo-server init
操作服务端
启动服务端
laravel-echo-server start
关闭服务端
laravel-echo-server stop
如果采用的是redis 广播,一定记得启动redis队列
php artisan queue:work --queue=default
代码准备
配置客户端
resources/assets/js/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 artisan make:event NoticeEvent
创建一个系统消息的事件
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class NoticeEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
protected $notice = '';
/**
* Create a new event instance.
* NoticeEvent constructor.
* @param $notice
*/
public function __construct($notice)
{
$this->notice = $notice;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('system');
}
// 处罚事件时返回的数据
public function broadcastWith()
{
return [
'data' => $this->notice
];
}
}
模版监听事件
window.Echo.channel('system')
.listen('NoticeEvent', (e) => {
console.log(e.data);
});
路由触发事件
routes/web.php
Route::get('/event', function (){
event(new \App\Events\NoticeEvent('这是一条系统通知'));
});
验证
通过以上步骤,即配置完成了公共频道点消息通知
通过浏览器Console 即可看到消息
私有频道
注册广播
取消注释–注册广播路由闭包函数授权 config/app.php
App\Providers\BroadcastServiceProvider::class,
创建事件
php artisan make:event LogisticsEvent
创建一个物流动态的通知
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class LogisticsEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
protected $notice = '';
/**
* Create a new event instance.
* NoticeEvent constructor.
* @param $notice
*/
public function __construct($notice)
{
$this->notice = $notice;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('logistics’); //私有管道
}
//触发事件时返回的数据
public function broadcastWith()
{
return [
'data' => $this->notice
];
}
}
设置频道权限
routes/channels.php
Broadcast::channel('logistics', function ($user) {
//本来是要从数据库查找,这里直接模拟
$ids = [1,2,3];
return in_array($user->user_id,$ids);
});
路由触发事件
将认证路由放到web.php中
Broadcast::routes();
//模拟登陆路由
Route::get('/login/user/{id}',function ($id){
auth()->loginUsingId($id);
});
//检测登陆路由
Route::get('/login/check', function (){
$res = auth()->check();
var_dump($res);
});
//触发路由--登陆之后再去触发
Route::get('/logistics', function (){
broadcast(new \App\Events\LogisticsEvent('这是一条物流通知'));
});
设置验证参数 CSRF 令牌
<meta name="csrf-token" content="{{ csrf_token() }}">
模版监听事件
window.Echo.private('logistics')
.listen('LogisticsEvent', (e) => {
console.log(e.data);
});
验证
通过以上步骤,即配置完成了公共频道点消息通知
通过浏览器Console 即可看到消息
聊天室
创建事件
创建房间
php artisan make:event Hello
<?php
namespace App\Events;
use App\User;
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 Hello implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public $roomId;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($roomId)
{
$this->user = auth()->user();
$this->roomId = $roomId;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('room.'.$this->roomId);
}
}
创建消息
php artisan make:event NewMessage
<?php
namespace App\Events;
use App\User;
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;
use Illuminate\Support\Facades\Log;
class NewMessage implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public $roomId;
public $msg;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($roomId, $msg)
{
$this->user = auth()->user();
$this->roomId = $roomId;
$this->msg = $msg;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('chat.'.$this->roomId);
}
}
配置路由
//房间路由
Route::get('/room/{roomId}', function ($roomId) {
broadcast(new \App\Events\Hello($roomId));
return view('welcome', ['roomId' => $roomId]);
});
//消息路由
Route::get('/room/{roomId}/{msg}', function ($roomId, $msg) {
broadcast(new \App\Events\NewMessage($roomId, $msg))->toOthers();
});
安装频道认证路由
routes/channels.php
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
// if ($user->canJoinRoom($roomId)) {
return ['id' => $user->user_id, 'name' => $user->nickname];
// }
});
安装聊天室到客户端
window.Echo.join(`chat.${roomId}`)
.here((users) => {
console.log(users);
})
.joining((user) => {
console.log(user.name + ' 来了');
})
.leaving((user) => {
console.log(user.name + ' 走了');
});
.listen('NewMessage', (e) => {
console.log(e.user.name + ":" + e.msg);
});
页面增加消息框
<input type="text" id="msg">
<button onclick="axios.get('/room/{{ $roomId }}/'+document.getElementById('msg').value)">发送</button>
验证
通过浏览器Console 即可看到消息
感兴趣的可以加下面QQ群!