HTML and CSS Reference
corresponding real-time server. Although most server-side frameworks provide event‐
ing mechanisms, few extend the events all the way through to the web browser to support
this real-time model. As a result, you are faced with retrofitting your current solutions
and architectures into this real-time model.
For example, suppose your server-side framework is capable of sending an event and
you have observers of this event in your code. WebSockets gives you the ability to extend
that event so that it carries all the way from the server side into the connected client's
browser. A good example would be to notify all WebSocket connections that a user has
registered on your site.
The first step towards implementing such a solution is to wire up the three main listeners
associated with WebSockets: onopen , onmessage , and onclose . Basically, the following
events will be fired automatically when a WebSocket connection opens successfully. For
objWebSocket . onopen = function ( evt )
alert ( "WebSocket connection opened successfully" );
objWebSocket . onmessage = function ( evt )
alert ( "Message : " + evt . data );
objWebSocket . onclose = function ( evt )
alert ( "WebSocket connection closed" );
After the WebSocket connection opens, the onmessage event fires whenever the server
sends data to the client. If the client wants to send data to the server, it can do so as
objWebSocket . send ( "Hello World" );
Sending messages in the form of strings over raw WebSockets isn't very appealing,
however, when you want to develop enterprise-style web applications. Because current
WebSocket implementations deal mostly with strings, you can use JSON to transfer data
to and from the server.
But how do you propagate the server-side events that are fired on the server and then
bubble them up on the client? One approach is to relay the events. When a specific
server-side event is fired, use a listener or observer to translate the data to JSON and
send it to all connected clients.
Relaying Events from the Server to the Browser
Before you can successfully communicate with a server, you need to know what you're
talking to and how. For the chapter's examples, I'm using the JBoss AS7 application