Aplikasi Realtime Menggunakan Socket.io Pada Framework Laravel
Aplikasi Realtime Menggunakan Socket.io Pada Framework Laravel - Membuat aplikasi realtime kini sudah sangat dibutuhkan sekali seperti halnya untuk menghitung jumlah pengunjung ke website setiap harinya, menghitung jumlah pembeli dan lain sebagainya.
Nah pada kali ini kita akan belajar membuat aplikasi realtime untuk menghitung pengunjung yang masuk ke halaman website.
1. Install Laravel
Di tutorial kali ini kita menggunakan laravel yang masih fresh, silakan ikuti command di bawah ini.
$ composer create-project --prefer-dist laravel/laravel realtimeApp
2. Install Vue JS
Sebelum lanjut ketahap berikutnya kita install terlebih dahulu vue js nya, dengan perintah dibawah ini.
$ npm install
3. Install Global Laravel Echo Server & Install Socket.IO client
Laravel echo merupakan library javascript untuk berlangganan saluran dan mendengarkan acara yang di siarkan Laravel. Dalam contoh ini kita akan menginstalkan paket socket.io karena kita akan menggunakan penyiar socket.io channel
$ npm install -g laravel-echo-server
$ npm install --save socket.io-client
4. Install Redis Laravel Package
Berhubung karena socket.io menggunakan redis kita perlu menginstall package redisnya.
$ composer require predis/predis
5. Penggunaan
Tambahkan source code di bawah ini ke dalam file resources/js/bootstrap.js.
import Echo from 'laravel-echo';
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.laravel_echo_hostname
});
Kemudian buka file welcome.blade.php di dalam folder resources, dan copas source code berikut
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>
Laravel Broadcast Redis Socket io
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>
Laravel Broadcast Redis Socket io
</h1>
<div id="notification"></div>
</div>
</body>
<script type="text/javascript">
window.laravel_echo_hostname = '{{ env('LARAVEL_ECHO_HOSTNAME') }}';
</script>
<script src="{{ env('LARAVEL_ECHO_HOSTNAME') }}/socket.io/socket.io.js" type="text/javascript"></script>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
<script type="text/javascript">
var i = 0;
window.Echo.channel('user-channel').listen('.UserEvent', (data) => {
i++;
$("#notification").append('<div class="alert alert-success">'+i+'. '+data.title+'</div>');
});
</script>
</html>
Buat file form.blade.php kurang lebih seperti ini source codenya.
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>
Laravel Broadcast Redis Socket io
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<div style="padding-bottom:20px;"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" name="message" id="message"></textarea>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<button class="btn btn-primary" onclick="sendMessage()">
Send
</button>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
window.laravel_echo_hostname = '{{ env('LARAVEL_ECHO_HOSTNAME') }}';
</script>
<script src="{{ env('LARAVEL_ECHO_HOSTNAME') }}/socket.io/socket.io.js" type="text/javascript"></script>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
<script type="text/javascript">
function sendMessage() {
jQuery.ajax({
url : '{{ url('hit') }}',
method : 'post',
data : 'message=' + jQuery('#message').val(),
headers : {
'X-CSRF-TOKEN' : '{{ csrf_token() }}'
},
success : function(r) {
console.log(r);
}
})
}
</script>
</html>
Buat 3 route sebagai berikut
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/','WelcomeController@index');
Route::get('form','WelcomeController@form');
Route::post('hit','WelcomeController@hit');
Edit WelcomeController.php dan ubah dengan source code dibawah ini.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WelcomeController extends Controller
{
public function index()
{
return view('welcome');
}
public function hit(Request $request)
{
event(new \App\Events\SendMessage($request->message));
return 1;
}
public function form()
{
return view('form');
}
}
Setelah itu buatlah 1 event dengan perintah berikut
$ php artisan make:event SendMessage
Berikut source code nya, kurang lebih seperti ini.
<?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;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
class SendMessage implements ShouldBroadcastNow
{
use InteractsWithSockets, SerializesModels;
public $data;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('user-channel');
}
/**
* The event's broadcast name.
*
* @return string
*/
public function broadcastAs()
{
return 'UserEvent';
}
/**
* The event's broadcast name.
*
* @return string
*/
public function broadcastWith()
{
return [
'title' => $this->data
];
}
}
Lalu tambahkan dibawah ini di dalam file .env
LARAVEL_ECHO_PORT=6001
LARAVEL_ECHO_HOSTNAME=http://127.0.0.1:6001
Setelah menambahkan source code di atas lalu jalankan perintah di bawah ini
$ npm run dev
$ php artisan serve
6. Informasi Tambahan
- Menjalan kan redis server as background
- Running laravel echo server
- Init laravel echo server
$ redis-server --daemonize yes
$ laravel-echo-server start
$ laravel-echo-server init