Java Reference
In-Depth Information
The Hypertext Transfer Protocol (HTTP) model was designed long before the Internet was popu-
lar, and it relied on simple specii cation and design. In the traditional HTTP model, a client opens
a connection to the back‐end server, sends an HTTP request of type 1 GET , POST , PUT , or DELETE ,
and the HTTP server returns an appropriate response. There have been several attempts to hack
and communicate over standard HTTP, such as AJAX, as well as design a new model such as
The traditional HTTP model has been cumbersome for almost any application that goes beyond
the simple get‐and‐submit‐content data model. Think about a chat client, in which the partici-
pants can send messages in any order, and hundreds can be chatting at the same time. The stan-
dard request‐response approach would be too limiting for such purposes. Some early approaches
to get past this limitation were AJAX and Comet. Both relied on long polling: opening an
HTTP connection and keeping it alive (maintaining the connection open) by not i nalizing the
With WebSockets, the client can initiate a raw socket to the server and execute full‐duplex commu-
nication. WebSockets support was introduced with JSR‐356. The package javax.websocket and its
server subpackage contain all classes, interfaces, and annotations related to WebSockets.
To i mplement WebSockets in Java EE, you need to create an endpoint class with the WebSocket life-
cycle methods shown in Listing 15‐1.
LISTING 15‐1: An example of an endpoint
package com.devchronicles.websockets;
public class HelloEndpoint extends Endpoint {
public void onOpen(final Session session, EndpointConfig config) {
session.addMessageHandler(new MessageHandler.Whole<String>() {
public void onMessage(String msg) {
try {
session.getBasicRemote().sendText("Hello " + msg);
} catch (IOException e) { }
The Endpoint class introduces three life-cycle methods: onOpen , onClose , and onError . At least the
extending class needs to implement the onOpen method.
You can deploy this endpoint in two different ways: either by coni guration or programmatically.
To programmatically deploy the code in Listing 15-1, your application needs to invoke the following:
ServerEndpointConfig.Builder.create(HelloEndpoint.class, "/hello").build();
Search WWH ::

Custom Search