Archive

Archive for March, 2012

NettoSphere: A WebSocket and HTTP server based on the Atmosphere and Netty Framework

Introducing NettoSphere, A Java WebSocket and HTTP server based on the Atmosphere and Netty Framework.  NettoSphere easily allow the creation of WebSocket and/or Comet applications. This blog will quickly demonstrate how simple and fast it take to build WebSocket application.

If you don’t know what is Atmosphere, take a quick look at this blog.

NettoSphere supports all Atmosphere API, which means you can write REST style application via Jersey or pure AtmosphereHandler. You start the server by doing:

   val server : NettoSphereServer = new NettyAtmosphereServer.Builder.config(
             new Config.Builder()
                .host("127.0.0.1")
                .port(8080)
                .resource(classOf[MyWebSocketEchoProtocol])
                .build)
             .build.start

As an example, you can write bi-directional WebSocket application by adding the following WebSocketProtocol:

class MyWebSocketEchoProtocol extends WebSocketProtocol with Serializable {

  override def onOpen(webSocket: WebSocket) {
    logger.info("Client's connected {}",
         webSocket.resource.getRemoteAddr )
  }

  override def onMessage(webSocket: WebSocket, message: String) {
      webSocket.write(message)
  }
}

Now client wise, any WebSocket library will works (like the jQuery.atmosphere.js, wCS or AHC), or using bare metal WebSocket API

    function showMessage(text) {
        document.getElementById('message').innerHTML = text;
    }

    var ws = new WebSocket('ws://' + document.location.host + '/echo');
    ws.onopen = function() { showMessage('Connected!'); };
    ws.onclose = function() { showMessage('Closed'); };
    ws.onmessage = function(msg) { showMessage(msg.data); };

That’s it. That doesn’t have to be complicated!! For more information, go to the NettoSphere main page or ping me on Twitter!

Categories: Atmosphere, Websocket