Websockets on Android

Have you ever tried to use Websockets on Android? In a recent project that I have been working on, it was required to use WebSockets to build a native Android app. Why a native app? Well, the current webkit that ships with the Android devices is not as fast as we would have liked. So, we had to figure out a way to build a native app that would be able to connect through WebSockets.

There are quite a few libraries available out there. And it took a bit of time to figure out the best library available. Well, the library isn’t that huge. The one that we finally decided to use had only 2 java files that got our work done. Simple, isn’t it?

The link to the source is here. You just need these two files:
1. WebSocket.java
2. WebSocketFactory.java

Out of these two files, the main file that you would be working on is the WebSocket.java. The WebSocketFactory.java, is just an extension of the other class that gives you WebSocket instances, based one of the two Drafts (75/76) that you request for. I am using the Draft-76 of the implementation.

For our use, we didn’t require the WebView portion embedded in the source. So we removed it.
This is how you instantiate and use a WebSocket.

WebSocket webSocket = new WebSocket(URI.create(“ws://yourserver.com”), DRAFT-76, “any_id”);

After you connect to the server, there are different event callbacks that you could listen for.

  1. onOpen() : This method will be called when the WebSocket is connected and ready for sending and receiving data.
  2. onClose() : This method will be called when the connection is terminated.
  3. onMessage() : This method will be called then a message is received over the socket.
  4. onError() : This method is used to notify any error message that might occur. According to the project doc on github, this currently doesn’t work properly.

When you need to send a message to the server, the WebSocket class has a send method which takes in a String as the message.

webSocket.send(“Your message”);

 To know more about the project, visit anismiles’ github project. Thanks anismiles. :)

13 thoughts on “Websockets on Android

  1. Good explanation, but could you provide a simple web app example? I have never used websockets and I need to use for my app, I have looked around and haven't seen any good tutorial on it. would please help with it?
    you can email me on billahill(at)gmail(dot)com

Leave a Reply

Your email address will not be published. Required fields are marked *