Java Reference
In-Depth Information
The deployed WebSocket is available from
ws://<host>:<port>/<application>/hello
. However, a
better way is to use annotation coni guration. Therefore, the same endpoint becomes Listing 15‐2.
LISTING 15‐2:
An example of an endpoint with annotations
package com.devchronicles.websockets;
@ServerEndpoint("/hello")
public class HelloEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText("Hello " + msg);
} catch (IOException e) { }
}
}
This approach lets you use annotations and keep up with the Plain Old Java Object (POJO)
approach because you are not extending a base class. The annotated endpoint has the same life-
cycle methods as the one in Listing 15‐2, but it introduces an additional
onMessage
life-cycle
method. Rather than implementing
onOpen
and adding the
onMessage
handler, it's enough to
implement an annotated
onMessage
method in the annotation‐based approach. You can anno-
tate several methods with
@OnMessage
to receive different types of data, such as
String
or
ByteBuffer
for binary.
The client‐side implementation of WebSockets depends on the web frameworks in use. However, a
simple JavaScript version is shown in the following snippet.
var webSocket = new WebSocket('ws://127.0.0.1:8080/websockets/hello');
webSocket.send("world");
A better example is to send a complex object in JavaScript Object Notation (JSON) format, which
can be marshaled to an object, as in the following code snippet.
var msg = {
type: "message",
text: "World",
date: Date.now()
};
webSocket.send(JSON.stringify(msg));
webSocket.onmessage = function(evt) { /* Expect to receive hello world */ };
WebSockets are great for building web applications that need persistent and asynchronous messag-
ing between the client and the server. Java EE offers an easy implementation of WebSockets. They
have far more coni gurations and implementation options than discussed here. If we have sparked
your interest in WebSockets we suggest you visit Oracle's Java EE Tutorial,
2
which explains in more
details how to program WebSockets using the Java API.