Reprinted by the author:
By: 88250
Time: January 1, January 1, 2010
We use a simple example to familiarize ourselves with HTML 5 websocket. In this example, the server increments an integer every second from 0 and sends it to the client browser for display. Preparation: Download jetty 7
, Java Web development environment, chrome 4 +
.
Server Java code:
Final public class countersocketservlet extends websocketservlet {
@ Override
Protected websocket dowebsocketconnect (final httpservletrequest HSR,
Final string ){
Return new countersocket ();
}
Final class countersocket implements websocket {
Private outbound;
Public void onconnect (final outbound ){
System. Out. println ("onconnect ");
This. Outbound = outbound;
}
Public void onmessage (final byte frame, final string data ){
System. Out. println ("onmessage ");
If (data. Equals ("Hello, server! ")){
New thread (){
@ Override
Public void run (){
Try {
Outbound. sendmessage (frame, "Hello, browser :-)");
Int I = 0;
While (true ){
Sleep (1000 );
Outbound. sendmessage (frame, String. valueof (I ++ ));
}
} Catch (final exception e ){
System. Err. println (E. getmessage ());
}
}
}. Start ();
}
}
Public void onmessage (final byte frame, final byte [] data,
Final int offset, final int length ){
Throw new unsupportedoperationexception ("not supported yet .");
}
Public void ondisconnect (){
System. Out. println ("ondisconnect ");
}
}
}
Browser client HTML code:
<HTML>
<Head>
<Title> websoket demo </title>
<SCRIPT type = "text/JavaScript">
If (! Window. websocket ){
Alert ("websocket not supported by this browser! ");
}
Function display (){
VaR valuelabel = Document. getelementbyid ("valuelabel ");
Valuelabel. innerhtml = "";
VaR Ws = new websocket (
"WS: // localhost: 8080/websocketdemo/counter-socket ");
WS. onmessage = function (EVT ){
Valuelabel. innerhtml = EVT. Data;
};
WS. onclose = function (){
};
WS. onopen = function (){
WS. Send ("Hello, server! ");
};
}
</SCRIPT>
</Head>
<Body onload = "Display ();">
<Div id = "valuelabel"> </div>
</Body>
</Html>
Run:
- Deployment
Copy the packaged websocketdemo. War to the jetty installation directory:
- Start Jetty
C:/jetty-distribution-7.0.1.v20091125> JAVA-jar start. Jar
- Test
Further reading:
- HTML 5 Specification
- Websockets specifications
- Websocket Protocol
- Jetty websocket Server
Resource:
- Latest chrome development version
- Jetty 7
- Resin 4