WebSockets have been around for a little while now, but haven’t quite reached the point of being mainstream; to some of us old-timers, something like Socket.io seems like the fevered dream of a madman, real-time communication between a web server and a client? What!?!
Fear not, gentle readers. It will all be clear soon.
A Little Background
Java has something of a stodgy reputation nowadays, a language used by large organizations to build applications for their accounting departments. That isn’t entirely fair. Sure, a lot of Java tools can commit sins like SimpleBeanFactoryAwareAspectInstanceFactory, and can make your eyes glaze over while reading esoteric XML config files. But there are also the good parts, like the incredible library support, the highly-tuned virtual machine that runs on almost any operating system, the ability to build real self-contained apps.
When working in Java one of the components I have ended up using often is Jetty, a wonderful embeddable web server that supports pretty much every feature you need, including SSL, WebSockets, custom request handlers, etc. This tutorial shows how to use Jetty to build a WebSockets-based application.
Intro to WebSockets
WebSockets provide a mechanism for full-duplex communication between a web server and client. A client (web browser) can open a socket with a web server. After this, the two can both write data to this socket and respond to messages coming from each other through event handlers registered on each side. Additionally, the server can broadcast messages to all of its connected clients. According to Wikipedia, WebSockets started trickling into browsers early in 2010 and are now available in all of the current major browsers, except for the naggingly resilient Android browser. Chrome on Android works well, however.
A Simple Chatroom
To demonstrate how WebSockets work with Java I’ve put together a simple chatroom application and tossed it up on GitHub. In addition to the source code, I’ve included a build of the application that can be run immediately. Once cloned, just go into the root directory of the checkout and type:
java -jar dist/JavaWebSockets.jar -p [some free port number]
After this you can point your browser (and perhaps even several browsers simultaneously to see the chatroom in action) to:
http://localhost:[some free port number]
Try sending a few messages to see how it works. Notice how the messages appear in each browser window instantaneously without the need to poll. This is one of the many powers of WebSockets.
How It Works: Server
JavaChatroom.java
JavaChatroom is the application class. It is a pretty standard Java application, and most of the work happens in the startServer() method. The code below initializes the ContextHandler for the WebSocket, and sets it to listen for requests coming in to the /chat route.
ContextHandler contextHandler = new ContextHandler();
contextHandler.setContextPath("/chat");
contextHandler.setHandler(new WebSocketHandler() {
public void configure(WebSocketServletFactory factory) {
factory.setCreator(new WebSocketCreator() {
public Object createWebSocket(UpgradeRequest req, UpgradeResponse resp) {
String query = req.getRequestURI().toString();
if ((query == null) || (query.length() <= 0)) {
try {
resp.sendForbidden("Unspecified query");
} catch (IOException e) {
}
return null;
}
return new ChatroomSocket();
}
});
}
});
A little further down, a second handler (a ResourceHandler) is added to the HandlerList which handles requests for the web files stored under /www in the application home directory.
ChatroomSocket.java
ChatroomSocket is the WebSocket itself. It is a subclass of WebSocketAdapter and overrides the various event handlers needed to make the WebSocket function. The interesting bits are below:
public void onWebSocketConnect(Session session) {
System.out.println("+++ Websocket Connect from " + session.getRemoteAddress().getAddress());
this.session = session;
JavaChatroom.getChatroom().addParticipant(session);
try {
this.session.getRemote().sendString(JavaChatroom.getChatroom().print(3));
} catch (IOException ex) {
System.out.println("+++ Websocket Error " + ex.getMessage());
}
}
public void onWebSocketText(String message) {
if(message != null && !message.equals("keep-alive")) {
ChatroomMessage crm = new ChatroomMessage(session.getRemoteAddress().getAddress().toString().substring(1), message);
JavaChatroom.getChatroom().addMessage(crm);
}
}
The onWebSocketConnect() method saves the Session for this socket to a local variable for later use, and also registers it as a participant with the Chatroom object so that messages from other users can be broadcast over this socket.
The onWebSocketText() method handles incoming text messages from the client, and adds them to the chatroom conversation.
Chatroom.java
The Chatroom class represents the chatroom itself, maintaining the history of the conversation and as well as the list of participants. In this simple implementation, there is a single instance of the Chatroom class, and a reference to it can be obtained from a static method on the JavaChatroom object.
public Chatroom() {
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
public void run() {
for (Session participant : JavaChatroom.getChatroom().participants) {
try {
participant.getRemote().sendString("keep-alive");
} catch (IOException ex) {
JavaChatroom.getChatroom().participants.remove(participant);
System.out.println("Websocket Error " + ex.getMessage());
}
}
}
}, 15, 15, TimeUnit.SECONDS);
}
public void addMessage(ChatroomMessage crm) {
this.messages.add(crm);
Vector<Session> sessionsToRemove = new Vector();
for (Session participant : this.participants) {
if (participant.isOpen()) {
try {
participant.getRemote().sendString(crm.print());
} catch (IOException ex) {
this.participants.remove(participant);
System.out.println("Websocket Error " + ex.getMessage());
}
} else {
sessionsToRemove.add(participant);
}
}
for(Session participant : sessionsToRemove) {
this.participants.remove(participant);
}
}
The constructor starts up a ScheduledExecutorService that messages each participant a keep-alive message every 15 seconds. This ensures that the clients stay connected and continue to receive conversation messages.
The addMessage() method first adds the new message to the conversation history, then iterates over the participant sessions and sends the new message to each in turn. Finally, it removes any participants who are no longer connected.
How It Works: Client
chat.js
$(document).ready(function() {
// connect the socket
var connection = new WebSocket('ws://' + document.location.host + '/chat/');
connection.onopen = function() {
console.log('Connection open!');
}
connection.onmessage = function(msg) {
if (msg.data !== 'keep-alive') {
$(".conversation").append(msg.data);
$('.conversation-window').scrollTop($('.conversation-window')[0].scrollHeight);
}
}
connection.onclose = function() {
console.log('Connection closed!');
}
// wire up the button
$('.send-button').on('click', function(e) {
e.preventDefault();
if ($('.message').val() != '') {
try {
connection.send($('.message').val());
$('.message').val('');
} catch (exception) {
console.log('Websocket error: ' + exception.message);
}
}
});
$('.message').keypress(function(event) {
if (event.keyCode == '13') {
$('.send-button').trigger('click');
}
});
});
The web application first connects to the server through a new instance of the WebSocket class and registers the event handlers. The onmessage() handler listens for incoming messages from the server and appends them to the conversation, while filtering out the “keep-alive” messages.
Finally, event handles are registered for clicking the Send button or hitting the Enter key. In either case, the message that is typed in the chat text box is sent via the socket to the server and the text box is cleared.
Wrapping Up
There you have it, a simple application demonstrating how to use WebSockets in Java.
There are many other ways in which these same concepts can be extended to create amazing applications. Imagine a client application that is notified in real-time whenever an object on the server side is updated, or a cooperative browser-based game in which each players’ position is relayed to their teammates instantaneously.
WebSockets are an enabling technology, giving us developers capabilities that just didn’t exist before.
Use them wisely!