【Laravel】Pusher를 사용해 본다
환경
PHP: 7.2.5
Laravel: 7.0
pusher-php-server: 4.1
Pusher로 앱 만들기
먼저 Pusher에 계정을 만드십시오.
로그인하면 새로 Channels App을 작성하는 화면으로 전환합니다.

먼저 Pusher에 계정을 만드십시오.
로그인하면 새로 Channels App을 작성하는 화면으로 전환합니다.

create apps for multiple environments를 선택하면 development, staging, production의 세 가지 환경의 앱을 동시에 만들 수 있습니다. Laravel에서 Public Channel을 사용해보십시오.
앱을 만든 후 먼저 전환하는 페이지의 Getting Started를 Laravel만 사용해 봅니다.
Step1 이벤트 수신 페이지 작성.
우선은 my-channel 의 my-event 라는 이벤트를 받는 페이지를 작성합니다.
Getting Started의 Step1에서 Javascript를 선택합니다.
거기에 쓰여진 index.html를 Laravel의 view에 작성합니다.
resources/views/pusher-index.blade.php<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/6.0/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher("{{ config('const.pusher.app_key') }}", {
cluster: "{{ config('const.pusher.cluster') }}"
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});
</script>
</head>
<body>
<h1>Pusher Test</h1>
<p>
Try publishing an event to channel <code>my-channel</code>
with event name <code>my-event</code>.
</p>
</body>
이때 app_key의 정보나 cluster의 정보를 그대로 쓰는 것은 위험하므로 상수로서 빼냅니다.
config/const.phpreturn [
'pusher' => [
'app_key' => env('PUSHER_APP_KEY'),
'cluster' => env('PUSHER_APP_CLUSTER'),
]
];
블레이드가 생성되면 라우팅을 설정합니다.
routes/web.phpRoute::group(['prefix' => '/pusher'], function () {
Route::get('/index', function () {
return view('pusher-index');
});
});
이것으로 이벤트를 받는 페이지가 완성되었습니다.
http://localhost:10080/pusher/index

Step2 이벤트 전송을 위한 엔드포인트 생성
다음은 이벤트를 발행하는 엔드포인트를 작성합니다.
우선 pusher의 라이브러리를 추가합시다.
composer require pusher/pusher-php-server
.env 에서 방금 만든 Pusher 앱 설정을 설명합니다.
앱의 키는 Getting Started 의 샘플내 또는 App Keys 탭에 기재되어 있으므로 그쪽을 참조해 주세요.
.envPUSHER_APP_ID=12345
PUSHER_APP_KEY=hoge-app-key
PUSHER_APP_SECRET=hoge-app-secret
PUSHER_APP_CLUSTER=hoge-cluster
broadcasting.php를 다시 씁니다. (Laravel7에서는 이미 설정되어 있으므로 필요하지 않습니다.)
config/broadcasting.phpreturn [
...
'connections' => [
'pusher' => [
...
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
],
],
]
];
그런 다음 이벤트를 발행하는 클래스를 만듭니다.
app/Events/MyEvent.phpnamespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MyEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return ['my-channel'];
}
public function broadcastAs()
{
return 'my-event';
}
}
마지막으로 이 이벤트를 호출하는 엔드포인트를 설정합시다.
routes/web.phpRoute::group(['prefix' => '/pusher'], function () {
Route::get('/index', function () {
return view('pusher-index');
});
// 追加
Route::get('/hello-world', function () {
event(new App\Events\MyEvent('hello world'));
return ['message' => 'send to message : hello world'];
});
});
동작 확인
실제로 작동하는지 확인해보십시오.
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/6.0/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher("{{ config('const.pusher.app_key') }}", {
cluster: "{{ config('const.pusher.cluster') }}"
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});
</script>
</head>
<body>
<h1>Pusher Test</h1>
<p>
Try publishing an event to channel <code>my-channel</code>
with event name <code>my-event</code>.
</p>
</body>
return [
'pusher' => [
'app_key' => env('PUSHER_APP_KEY'),
'cluster' => env('PUSHER_APP_CLUSTER'),
]
];
Route::group(['prefix' => '/pusher'], function () {
Route::get('/index', function () {
return view('pusher-index');
});
});
composer require pusher/pusher-php-server
PUSHER_APP_ID=12345
PUSHER_APP_KEY=hoge-app-key
PUSHER_APP_SECRET=hoge-app-secret
PUSHER_APP_CLUSTER=hoge-cluster
return [
...
'connections' => [
'pusher' => [
...
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
],
],
]
];
namespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MyEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return ['my-channel'];
}
public function broadcastAs()
{
return 'my-event';
}
}
Route::group(['prefix' => '/pusher'], function () {
Route::get('/index', function () {
return view('pusher-index');
});
// 追加
Route::get('/hello-world', function () {
event(new App\Events\MyEvent('hello world'));
return ['message' => 'send to message : hello world'];
});
});


참고 자료
Pusher 공식 문서
Pusher로 WebSocket 통신 시도
Reference
이 문제에 관하여(【Laravel】Pusher를 사용해 본다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/akkino_D-En/items/9d6e49c5f7aa41e31021텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)