HTML and CSS Reference
In-Depth Information
This code first checks whether the browser supports server-sent events. It does so by checking for the
existence of the
window.EventSource
object.
The code then proceeds to wire the
click
event handler of the Start Listening button. This event
handler creates a new
EventSource
object. The path of the ASP.NET generic handler that sends the events is
passed as the parameter while creating the
EventSource
.
Event handlers are then wired for the
EventSource
object's three events:
open
,
message
, and
error
. The
open
event is raised when the browser makes a request to the server resource for the first time. When the
data sent by the server arrives at the client, the
message
event is raised. In case of an error, such as closed
connection, the
error
event is raised. The
open
and
error
event handlers add a message to the
targetDiv
<div>
element. The error handler uses the
eventPhase
property to decide whether the underlying
connection is closed. The possible values for
eventPhase
are
CONNECTING
(
0
),
OPEN
(
1
), and
CLOSED
(
2
). The
message
event handler receives an
event
parameter, and its
data
property returns the data sent by the
server.
The server-side code that sends the events to the client resides in the ASP.NET generic handler,
ClientNotifier.ashx.
. This code is shown in Listing 11-14.
Listing 11-14.
Sending Events to the Client
public void ProcessRequest(HttpContext context)
{
HttpResponse Response = context.Response;
DateTime startDate = DateTime.Now;
Response.ContentType = “text/event-stream”;
while (startDate.AddMinutes(1) > DateTime.Now)
{
Response.Write(string.Format(“data: {0}\n\n”, DateTime.Now.ToString(“hh:mm:ss”)));
Response.Flush();
System.Threading.Thread.Sleep(15000);
}
Response.Close();
}
This code sets the
ContentType
of the
Response
to
text/event-stream
. This way, the client browser
knows that this response belongs to server-sent events. A
while
loop then iterates for 1 minute. Within the
loop, the event data is dispatched to the client in batches. The
Response.Write()
method writes the event
data on the response stream, and
Response.Flush()
ensures that it's sent directly to the client without any
buffering. The event data sent to the client must be in a predefined format. A sample format is as follows:
data: Hello World!\n\n
Every piece of event data should begin with
data:
and end with two newline characters (
\n\n
). The
event data can also be sent in multiple-line format:
data: {\n
data: “CustomerID”: “ALFKI”,\n
data: “Country”: “USA”\n
data: }\n\n
This markup sends data to the client in JSON format. The client can parse the data to construct a
JSON
object.
The operation is halted for 15 seconds using the
Thread.Sleep()
method, to introduce a delay
between notifications. In addition to the developer-defined data, the server also sends the client a unique