Created
July 4, 2017 14:19
-
-
Save rajitha-bandara/476a9c91257405fb1d76f67e2e4cf5a4 to your computer and use it in GitHub Desktop.
Laravel Server Sent Events
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
use Symfony\Component\HttpFoundation\StreamedResponse; | |
$response = new StreamedResponse(function() use ($request, $data) { | |
while (true) { | |
echo 'data: ' . json_encode(['data' => $data]) . "\n\n"; | |
ob_flush(); | |
flush(); | |
usleep(10000000); | |
} | |
}); | |
$response->headers->set('Content-Type', 'text/event-stream'); | |
$response->headers->set('X-Accel-Buffering', 'no'); | |
$response->headers->set('Cach-Control', 'no-cache'); | |
return $response; | |
In JS, | |
if (!!window.EventSource) { | |
var req_url = "{{route('ajax.booking_alerts')}}"; | |
var source = new EventSource(req_url); | |
source.addEventListener("message", function(e) { | |
alerts_last_check = e.data.alerts_last_check; | |
console.log(e.data); | |
}, false); | |
source.addEventListener("open", function(e) { | |
console.log("Connection was opened."); | |
}, false); | |
source.addEventListener("error", function(e) { | |
console.log("Error - connection was lost."); | |
}, false); | |
} else { | |
alert("Your browser does not support Server-sent events! Please upgrade it!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment