Document Version 1.0
Copyright © 2012-2013 firstname.lastname@example.org
Beside Server-Sent Events, WebSocket is an another important feature introduced by HTML5 for browser to update web page content automatically from server. The most important differences between WebSocket and Server-Sent Events are:
- Server-Sent Events is one way communication whereas WebSocket use full-duplex channel.
- Server-Sent Event is HTTP, WebSocket introduced new protocol "ws" protocol
Here I am not going compare WebSocket and Server-Sent Events in detail, I will just show you a simple WebSecket sample to get a feeling.
A sample of Server-Sent Events could be found here http://milestonenext.blogspot.de/2013/07/html5-server-sent-events-sample-with.html
In the example below, browser opens a window, send text message to server. Server just send message back to browser, shown in the window. (by the way, the sample could be extended with small effort to work as a chat application ...)
1. Create a simple web application "WebSocketSample"
User your favorite IDE (I use Eclipse) to create a Web Application. Be sure to use servlet 3.x style.
The sample web application consists of :
- two java classes, which are the server side code
- one "html" page which is the client
The sample uses Tomcat implementation of of "WebSocket", so we need to have "catalina.jar" on class path.
Add servlet-api.jar to class path as well.
Since Tomcat's WsOutbound has indirect dependency on "tomcat-koyote.jar", please add this jar to class path to resolve compile error like "the hierarchy of the type ... is inconsistent ..."
5. Export ".war" and deploy it on a running Tomcat
Export the "WebSocketSample.war"and deploy it on a running Tomcat server.
Open the link below with browser:
You will see:
Now type your name and send:
6. The "WebSocket" Header
When we take a close look at the headers of the Request and Response above: