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.
webSocket.connect();
- 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.
webSocket.send("Your message");To know more about the project, visit anismiles' github project. Thanks anismiles. :)