Archive

Archive for February, 2012

Writing Client/Server WebSocket Application using Scala

February 10, 2012 3 comments

Today I will explains how to quickly write a WebSocket application in Scala. I will show how easy it is to write both client and server side. For the client I will use the wCS library, and for the server I will use the Atmosphere’s WebSocket Framework. If you expect something complex, don’t read this blog!

OK let’s write a really simple application which echo messages received to all connected clients. Messages can be initiated by the client or by the server itself. In order to achieve that, we will use the Atmosphere Framework. If you aren’t familiar with Atmosphere, take a look at this introduction. What we need to define is a Scala class that will be invoked by the framework when a WebSocket message is received. With Atmosphere, it as simple as:

import javax.ws.rs.{POST, Path}
import org.atmosphere.annotation.Broadcast
@Path("/")
class Echo {

  /**
   * Broadcast/Publish the WebSocket messages to all connection WebSocket clients.
   */
    @POST
    @Broadcast
    def echo(echo : String) : String = {
      echo
    }
}

The echo method will be invoked with a String arguments who represent a WebSocket message. The message will be distributed using an Atmosphere Broadcaster, which can be seen as a bi-directional channel of communication between clients and server. Looking for more code? Well, with Atmosphere you don’t need more on the server side as the framework take care of the WebSocket’s handshake and all the protocol details you don’t want to spend time on it.

Now on the client side, let’s use the wCS library (Asynchronous I/O WebSocket Client for Scala). First, let’s open a connection to the server

    val w = new WebSocket
    w.open("ws://127.0.0.1/")

Once the WebSocket connection is established, we can now send message (as String or Bytes).

    w.send("foo")

To receive WebSocket messages, all we need to do is to pass a Listener that will be invoked when the server echo messages

    w.listener(new TextListener() {

      override def onMessage(s : String) {
          // Do something with the message
      }

    })

We can switch at any moment between String and Bytes, and associate as many Listener as we can. Note that the library is fully asynchronous and never the send operation is “non blocking”. We can fluidly write the code above by just doing:

    val w = new WebSocket
    w.listener(new TextListener() {

      override def onOpen(){
        // do something
      }

      override def onMessage(message: String) {
        // do something
      }

      override def onClose() {
        // do something
      }

    }).open("ws://127.0.0.1").send("foo")

That’s all. You just wrote your first WebSocket client/server application using Scala! For more information, ping me on Twitter!

Categories: Atmosphere, WCS, Websocket
Follow

Get every new post delivered to your Inbox.

Join 50 other followers