WebSockets in Java

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.

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:

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.

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

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! 

Do It Yourself

Let me alone cause no one wants to be
Hanging around with someone messing up like me
I guess my way isn't good enough
When I try I just keep on wrecking stuff

Bouncing Souls, "Argyle"

Everyone carries different baggage with them into their chosen field. I don't mean "baggage" in the strictly negative sense; some baggage can be pretty helpful, like Batman's utility belt or Felix's Bag of Tricks. 

For me that baggage is punk rock.

I don't just mean the music. I mean the lifestyle, the feelings it evokes, the outsiderness and otherness. All of it. As an introvert, I wasn't the most social kid while growing up. Late in my high school career I discovered punk rock. Seeing people who were able to be cool without fitting in to mainstream culture, who weren't afraid to stand out. There was a lot of conformity in the semi-rural area where I went to high school, and these kids with the faster-louder music blaring from their car stereos seemed to offer a glimpse of something more exciting. I was hooked.

By the time I was at university, my whole social experience (what there was of it; I was still an introvert) was dictated by this music. I went to all of the parties, watched all my friends' bands, hung out at their radio shows. I eventually started playing bass myself, and listened mostly to relatively obscure early 80's English bands who often couldn't play and definitely couldn't sing.

Eventually I started to grow up. My taste in music changed, and I came to internalize my otherness rather than feel a need to be part of the scene or dress a particular way. I never forgot the feelings punk rock gave me, and keep many of the values to this day.

Chief amongst those values is the "Do It Yourself" aesthetic, often shortened to DIY. The idea behind this is that the barriers between amateurs and professionals in a given field are often artificial, and if you work hard enough, you can create something of value even if you lack the formal training. Sure, it might not be as pretty, but it's yours, damn it. And people better pay attention.


Recently I've been doing lots of work with different PHP frameworks and content management systems. Naturally there were some things I liked about each; for instance, the Yii Framework (a pretty standard MVC) has a cool routing system based on regular expressions, and WordPress (the venerable CMS) has themes, which are pretty useful for when you want to share a common backend across several client sites. There were also some things I disliked. Yii's database layer for example; it isn't bad as far as ORMs go (they all have problems) but it certainly gives developers enough rope to hang themselves, and I had to spend a lot of time stripping it out of certain parts of a client app when the queries it was generating were taking 10 times longer than they should have.

There was definitely room for improvement here, so I decided to give it a shot. The result is Sodapop, my first (complete) PHP MVC framework

It's still under active development, but it's pretty useful already. It follows the standard MVC pattern of having controller objects with action methods, model objects that represent rows in the database, layouts and view templates named based on their controller and action. It also has some unique features, such as themes and model classes that can be declared implicitly the first time they are invoked. 

There is still a lot I'd like to add to it, particularly around the database layer. Relations, migrations, support for other servers, stuff like that. But you know what? That's fine. It's something I made for my own projects and I can add to it as I need to while maintaining an internal consistency. If other people like what it offers, I'd love to have them along for the ride with me, offering suggestions and telling me where it needs improvement. Truthfully though, I'd make it even if nobody else looked at it. It's just fun to learn how these things work.

One could justifiably ask what the point is in creating something like a new web framework when there are already so many; aren't there some things where doing it yourself is just an exercise in ego gratification? Sure, there is that. But it's worth looking at the bigger picture.

Careers in our industry are frighteningly long, especially if you want to stay technical and not move into management. At any given time there are lots of sexy tools; today (at least in the PHP world) we have Laravel, Symfony, Yii, and myriad others. If you looked at it a few years ago, though, you would have seen a slightly different list, with Zend, CakePHP, and others at the top of the heap. 

The tools you use will always change, and you'll have to be learning all the time to survive.

While you do need to have a general competence and familiarity with popular tools, as well as the ability to get up to speed quickly, I would rather know concepts than dedicate my life to learning every intricacy of a specific tool. And there is no better way to learn concepts than doing it yourself.

When it comes to building websites for clients, I tend to use whichever framework they are comfortable with, including the popular ones. For my own projects, I want to have more control, and the ability to build in features that I'll still be able to leverage in 5 years after the frameworks du jour have splintered and been replaced by some new hotness. And I'll continue to refine my own tools to incorporate the good parts of the new frameworks that come out.


One of the magical things about being a programmer is that it affords you the ability to create the world that you live in. Programs have many components, and you can use components created by others, or use your own. You choose your own level of engagement. I can't think of any other field that offers that.

There is an art in having the self-awareness to know if what you are adding is creating value, or is just different for the sake of different. It can be fun to reinvent the wheel, but you won't necessarily improve on the original. 

Doing it yourself under the right parameters can help push your boundaries and grow as a developer. It can teach you how to design good systems and help you understand the tradeoffs that go into building such systems. It can also get you out of the cycle of reapplying the same patterns to solve new problems by giving you new tools to work with.

When I lose, every time I win, cause no one will ever be
Messing up stuff and doing things wrong quite like me
No one will ever be like me
No one will ever be like me

SASS and Transitional Technologies

I was first introduced to SASS early last year. The agency I was working with at the time (Evolution Bureau) began having a series of tech talks amongst the developers where we would introduce each other to different technologies we were excited about; my friend Josh gave a little presentation about his favorite CSS preprocessor.

For those who aren't familiar, SASS is a CSS extension language. The syntax is immediately familar to anyone used to writing CSS, but it includes many handy capabilities that naked CSS doesn't have, such as variables, nesting, functions and mixins. There is a compiler that can be set to monitor your SASS directories which will compile your SASS documents into CSS every time you save them, making them easy to work into your normal development flow. The result is much more maintainable stylesheets.

Needless to say, it looked impressive. But something about it just didn't feel right to me.

It seemed weird to have a critical part of an application (the stylesheets) entirely generated by a tool running on a developer's machine. I couldn't quite put my finger on why, exactly; it's just weird. Like, say there is some old website quietly humming along somewhere for a couple years. All the original developers have left, and you get tasked with updating some of the pages. Mostly just content updates, but a lot stuff needs to be rearranged and formatted. You download the site locally, pop open the CSS file to start your work and what do you see? Thousands of lines of machine-generated CSS rules. Maybe you can find the original SASS file on there somewhere (it isn't technically used by the production site, so there is a chance it wasn't pushed) but even then you have to set up your local machine to compile it and drop it in the same directory as the old files.

It's sort of like a code smell. Your code is no longer self-contained, and if SASS were to get hit by a bus tomorrow, your site would be very hard to update.

Fast forward a few months. I started work on another project with a different company, building a responsive site with Foundation. I had to start using SASS every day. And you know what?

It really is awesome. I'm not sure I would go back to using naked CSS if given the choice.

An article I read last week reminded me of my original thoughts about SASS, though. Matt Greer wrote Coffeescript's Time is Waning to explain the reasons why he won't likely use Coffeescript going forward; roughly speaking, Coffeescript is to Javascript what SASS is to CSS. 

The core of his argument is that as Javascript/ECMAScript is evolving, it is incorporating many of the features that made Coffeescript compelling; as browsers (and Node.js) start to support the newer standards, he is finding the friction of using the intermediate language to be harder to justify.

I could easily see something similar happening to CSS. Coding with SASS and other preprocessors is just so much more efficient that it seems inevitable that standards bodies and browser vendors will start bringing their best features into the core product, ultimately making them redundant. And this is as it should be.

Some technologies are transitional by nature, a bridge that must exist from the "bad old days" to something new and better. I think "transitionalness" is what I couldn't put my finger on originally; that as great as the tool is, the fact that it isn't a core technology made it feel like a mile marker rather than an final destination.

Of course, we don't know what the future looks like. In the meantime, I'll continue to pick the best tool for the job.