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 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.
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 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:
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.
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.
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
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.
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!
If you like this post, you should follow me on Twitter.