Over a million developers have joined DZone.

Clojure: Web Socket Introduction

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Web Sockets may sound intimidating, but if you use Clojure and jQuery it's actually quite simple.

The first thing you need to do is grab a WebSocket capable server. Jetty is a decent option, but (Joe Walnes' recently released) webbit was the fastest choice for getting up and running.

You'll probably want to:

git clone https://github.com/joewalnes/webbit.git
cd webbit
make jar

At that point you should have both build and lib directories in your webbit directory. You'll want to copy webbit/build/webbit.jar and webbit/lib/netty-3.2.3.Final.jar to a new directory where you're going to create your Web Socket application. You might as well create a blank server.clj and index.html as well. Now you should have a directory that looks something like this:

-rw-r--r--  1 jfields  jfields     674 Feb  7 08:58 index.html
-rw-r--r-- 1 jfields jfields 786229 Feb 6 10:49 netty-3.2.3.Final.jar
-rw-r--r-- 1 jfields jfields 693 Feb 7 08:58 server.clj
-rw-r--r-- 1 jfields jfields 59616 Feb 6 10:49 webbit.jar

Next we'll get webbit fired up using Clojure. The webbit README gives us a java example that is easily convertible. The following code starts a server and prints it's args when a web socket is opened, closed, or sent a message.

(ns server
(:require [clojure.contrib.json :as json]
[clojure.string :as s])
(:import [webbit WebServer WebServers WebSocketHandler]
[webbit.handler StaticFileHandler]))

(doto (WebServers/createWebServer 8080)
(.add "/websocket"
(proxy [WebSocketHandler] []
(onOpen [c] (println "opened" c))
(onClose [c] (println "closed" c))
(onMessage [c j] (println c j))))

(.add (StaticFileHandler. "."))

(println "server up")

That's it. The server doesn't do much, but it's up and running. Start it up if you'd like.

java -cp clojure.jar:webbit.jar:netty-3.2.3.Final.jar:clojure-contrib-1.2.0.jar clojure.main server.clj

(note: I'm using Clojure 1.2)

If all went well, you should see "server up" printed to the console. We'll leave the server running for now and put together a simple client.

Again, the examples already on the internet give us 90% of what we need. We're going to use jquery-websocket, and the example at the bottom of the page is just about exactly what we need. The following code is a slightly modified version that should suit our purposes.

<h1>WebSocket Demo</h1>
<input id="message" type="text"/>
<section id="content"></section>
<script src="http://www.google.com/jsapi"></script>
<script>google.load("jquery", "1.3")</script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js">
<script src="http://jquery-websocket.googlecode.com/files/jquery.websocket-0.0.1.js">
var ws = $.websocket("ws://", {
events: {
upcased: function(e) { $("#content").html(e.message); }}});

ws.send('message', {type: "downcase", message: $("#message").val()});});

Our client isn't much, but it does connect to a web socket and it sends a message to the web socket when the text in the input is changed.

Assuming you still have the server running you should be able to load up your page.

Is your page not loading? =(
What URL did you use? I've been told http://localhost:8080/ doesn't work as well as
What browser did you use? Everything works for me in Chrome (version 8.0.552.237)
If your page loads, your server must be up and running. You should see something similar to the following line in your server console.
opened #<NettyWebSocketConnection webbit.netty.NettyWebSocketConnection@8c5488>
You might as well type something into the input and tab out (or whatever you prefer to do that fires the "change" event). I typed in "hello" and got the following output in my server console.
#<NettyWebSocketConnection webbit.netty.NettyWebSocketConnection@8c5488> {"type":"message","data":{"type":"downcase","message":"hello"}}
Okay, everything is working. Let's add a little behavior to our server. Upon receiving a message, our server is going to take the text, upcase it, and send it back to the client.

Here's an updated version of server.clj.
(ns server
(:require [clojure.contrib.json :as json]
[clojure.string :as s])
(:import [webbit WebServer WebServers WebSocketHandler]
[webbit.handler StaticFileHandler]))

(defn on-message [connection json-message]
(let [message (-> json-message json/read-json (get-in [:data :message]))]
(.send connection (json/json-str {:type "upcased" :message (s/upper-case message) }))))

(doto (WebServers/createWebServer 8080)
(.add "/websocket"
(proxy [WebSocketHandler] []
(onOpen [c] (println "opened" c))
(onClose [c] (println "closed" c))
(onMessage [c j] (on-message c j))))

(.add (StaticFileHandler. "."))

(println "server up")
The new version of server.clj takes advantage of clojure.contrib json support. The net result of this is that we can work with Clojure maps and basically ignore json throughout our application.

After making the above changes to server.clj we can restart our server, refresh our webpage, enter some text, tab out of the input, and then we should see our text on the webpage as upper-case.

And, we're done. We have working client-server interaction. We're ready to put this into production. It's that easy.

You might have noticed a few things that make the magic happen. On the server we sent a map that has :type "upcased". This type corresponds to the events that are defined in our client. The jquery-websocket takes care of routing our new message to the function associated with upcased. Extending on this idea, you can send messages from the server with different types and handle each one on the ui as a different event.

That's it. The app should be working, and you should have everything you need to begin expanding the capabilities of the application. If you run into any trouble, the documentation for webbit and jquery-websocket should get you through.

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.


Published at DZone with permission of Jay Fields, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}