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?
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.
- onOpen() : This method will be called when the WebSocket is connected and ready for sending and receiving data.
- onClose() : This method will be called when the connection is terminated.
- onMessage() : This method will be called then a message is received over the socket.
- 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.
To know more about the project, visit anismiles’ github project. Thanks anismiles. 🙂