Motyar

Simple Chat Application with HTML5 Server-Sent Events

Lets talk about HTML5's one of fancy feature Server-Sent Events that can be defined as

"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: , , , , , ,


By :