Simple Chat Application with HTML5 Server-Sent Events
"API for opening an HTTP connection for receiving push notifications from a server".
Why Server-Sent Events when there is WebSockets?
WebSockets is richer protocol to perform bi-directional, full-duplex communication. WebSockets are useful where we need two-way, real-time updates in both directions; and can be used in Games, chat app.When we simply need updates from some server action, like updating news, stocks or feeds. Server-Sent Events are your friend. SSEs have special features like automatic reconnection, event IDs, and the ability to send events. And doesn't require full-duplex connections and new Web Socket servers to handle the protocol.
Idea
In this post we will talk about the basic parts, implementation and using it to write a simple chat application. We ll be using PHP on server side.JavaScript API
var source = new EventSource('/news/');
source.onmessage = function(e) {
alert('We got new news:'+e.data);
}
Server
Server must send plaintext response, served with a 'Content-Type: text/event-stream'
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function sendMsg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
Simple chat application
I wrote a simple chat application using this technique. You can see a demo here.Share the post if you enjoyed reading and think its useful.
Labels: Application, html5, Javascript, php, resource, SSEs, Tutorials
By : Motyar+ @motyar14 comments
John says…
Avatar Html5 Video Player says…
Obscuro Luar says…
Manoj K says…
hitesh says…
Paul Jay says…
says…
says…
ಶ್ರೀಪತಿ ಗೋಗಡಿಗೆ says…
says…
Otherwise, works great in Chrome and Firefox. I've also been reading up and playing with your source and see that if you modify the server and add: echo "retry: 1000" . PHP_EOL; -- Then you will get responses much quicker than the default of "about 3 seconds".
Motyar D says…
@Anonymous its retry: 100 in demo. thanks for tip.
@ ಶ್ರೀಪತಿ ಗೋಗಡಿಗೆ with which browser you are trying?
@Paul Jay added fallback, it should work with all browsers now.
@hitesh @manoj @john thanks guys.
says…
SA says…
Deepak Sharma says…
can you please assist me?
I have a problem as we know in server sent event it automatically sent the push msg to client after every 3 sec, and we can change this time.
But my problem is I want to trigger this sending msg to client on database update. Please help me out.
consider
File1 - which subscribed the event source to the file2
file2 - send the live stream to client a php file.
file3 - has a function, used to insert the value in DB.
now I want if I call function in file3 to insert the value only then file2 send the msg to clients..
Please help me out..


Post a Comment