Notifikasi realtime adalah fitur penting untuk aplikasi modern seperti marketplace, chat, transaksi online, dan dashboard admin. Pada artikel ini, kita membahas dua teknik populer: WebSocket dan Firebase Cloud Messaging (FCM).
1. Apa Itu Notifikasi Realtime?
Notifikasi realtime berarti informasi dikirim ke pengguna tanpa mereka harus melakukan refresh. Data dikirim secara langsung dari server ke client saat event terjadi.
2. Menggunakan WebSocket
WebSocket adalah teknologi yang memungkinkan komunikasi dua arah antara server dan client.
Contoh Server WebSocket (PHP Ratchet)
// server.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class NotifServer implements MessageComponentInterface {
public function onMessage(ConnectionInterface $conn, $msg) {
foreach ($conn->httpRequest->connections as $client) {
$client->send($msg);
}
}
}
Client WebSocket (JavaScript)
const socket = new WebSocket("ws://localhost:8080");
socket.onmessage = function(event) {
console.log("Notifikasi masuk:", event.data);
};
WebSocket cocok untuk:
- Aplikasi chat
- Monitoring realtime
- Dashboard admin
- Game multiplayer
3. Menggunakan Firebase Cloud Messaging (FCM)
Firebase Cloud Messaging (FCM) adalah solusi paling mudah untuk push notification di Android, iOS, dan Web.
Contoh Mengirim Notifikasi FCM dengan PHP
$serverKey = "YOUR_FIREBASE_SERVER_KEY";
$token = "DEVICE_TOKEN";
$data = [
"to" => $token,
"notification" => [
"title" => "Pesan Baru",
"body" => "Anda menerima pesan baru!"
]
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"Authorization: key=" . $serverKey,
"Content-Type: application/json"
]);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
Kelebihan FCM:
- Gratis
- Sangat stabil
- Mudah diintegrasikan
- Cocok untuk aplikasi Android
4. WebSocket vs Firebase
| WebSocket | Firebase |
|---|---|
| Realtime 100% live | Tidak selalu live, tapi push notification cepat |
| Butuh server sendiri | Tidak perlu server tambahan |
| Cocok untuk chat & dashboard | Cocok untuk mobile notification |
5. Best Practice Notifikasi Realtime
- Gunakan SSL untuk keamanan WebSocket.
- Terapkan autentikasi sebelum client menerima notifikasi.
- Gunakan pesan singkat agar cepat dikirim.
- Gunakan queue (RabbitMQ, Redis) untuk traffic besar.
Dengan WebSocket atau Firebase, Anda dapat membangun sistem notifikasi yang cepat, aman, dan responsif untuk kebutuhan aplikasi modern.