Created
May 17, 2019 15:41
-
-
Save romaricdrigon/328ac62c10d15fbe762b8b253a98f9e9 to your computer and use it in GitHub Desktop.
Exemple d'utilisation de Mercure pour un widget affichant des scores en temps réel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Score en temps réels</title> | |
</head> | |
<body> | |
<div id="scoreBoard"></div> | |
<script> | |
// On va se placer sur le topic "demo" partout dans cet exemple | |
var topic = 'demo'; | |
var scoreBoard = document.querySelector('#scoreBoard'); | |
// Note: je vais utiliser partout ici des templates litterals JS, plus lisibles, | |
// au lieu de quotes on a des backtics (`), et deans on peut afficher des variables avec ${}. | |
// La syntaxe va vous rappeler PHP old-school :) | |
scoreBoard.insertAdjacentHTML('beforeEnd', `Écoute du topic ${topic}`); | |
// localhost est l'adresse du serveur Mercure | |
const url = new URL('http://localhost/hub'); | |
// Et on rajoute les topics auxquels s'inscrire (en paramètre GET) | |
url.searchParams.append('topic', `http://localhost/${topic}`); | |
const eventSource = new EventSource(url); | |
// Ce callback sera appelé à chaque réception de message | |
eventSource.onmessage = function(event) { | |
console.log(`Reçu un message avec l\'ID ${event.lastEventId}`); | |
const details = JSON.parse(event.data); | |
scoreBoard.insertAdjacentHTML('beforeEnd', `<p>${details.eventName}</p>`); | |
}; | |
console.log('Client démarré!'); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Un token a été calculé à partir de la clef secrète clef-privee-2-romaric-net1nf | |
define('PUBLIC_JWT', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InN1YnNjcmliZSI6WyJmb28iLCJiYXIiXSwicHVibGlzaCI6WyJmb28iXX19.XCriHjQZJ-s24o1LH_5sRo2X9RCKJgizdQOG0aH1zMM'); | |
$topic = 'demo'; | |
// On lit le nom des paramètres de notre script, sinon ce sera "Romaric" par défaut | |
$name = isset($argv[1]) ? $argv[1] : 'Romaric'; | |
$postData = http_build_query([ | |
// On se place sur localhost:80, sur notre topic | |
'topic' => 'http://localhost/'.$topic, | |
'data' => json_encode([ | |
'eventName' => sprintf('%s a marqué un point!', $name), | |
]), | |
]); | |
// Il suffit d'une requête POST! | |
$r = file_get_contents('http://localhost/hub', false, stream_context_create(['http' => [ | |
'method' => 'POST', | |
'header' => "Content-type: application/x-www-form-urlencoded\r\nAuthorization: Bearer ".PUBLIC_JWT, | |
'content' => $postData, | |
]])); | |
if (!$r) { | |
echo sprintf("Erreur lors de l'envoi du message: %s\n", $r); | |
} | |
echo sprintf("Le message a bien été envoyé, reçu un ID: %s\n", $r); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment