DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Clojure: Web Socket Introduction

Clojure: Web Socket Introduction

Jay Fields user avatar by
Jay Fields
·
Feb. 08, 11 · Interview
Like (0)
Save
Tweet
Share
5.97K Views

Join the DZone community and get the full member experience.

Join For Free

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. "."))
(.start))

(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.
<html>
<body>
<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>
<script src="http://jquery-websocket.googlecode.com/files/jquery.websocket-0.0.1.js">
</script>
<script>
var ws = $.websocket("ws://127.0.0.1:8080/websocket", {
events: {
upcased: function(e) { $("#content").html(e.message); }}});

$('#message').change(function(){
ws.send('message', {type: "downcase", message: $("#message").val()});});
</script>
</body>
</html>
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 http://127.0.0.1:8080/
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. "."))
(.start))

(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.

 

From http://blog.jayfields.com/2011/02/clojure-web-socket-introduction.html

Clojure

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Boot, Quarkus, or Micronaut?
  • Container Security: Don't Let Your Guard Down
  • Tracking Software Architecture Decisions
  • Monolithic First

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: