Socket in android with node.js server and Socket.io

Updated 15 December 2016

Save

Socket in android can be implemented with java.net.Socket but as we are implementing socket connection with node.js server having Socket.io hence we are using here socket.io for client side as well . Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. But its quiet easy to setup with node.js server. The only drawback of Socket.io is that a client supporting standard WebSocket to not be able to contact a Socket.IO server. And a Socket.IO implementing client cannot talk to a non-Socket.IO based WebSocket or Long Polling Comet server.

But remember it works only for node.js 1.0, if you are using 0.9 then upgrade. For upgrade please follow the link.

So now your server is ready to enable the connection at client side. Firstly lets write the code for initializing socket we are doing it by making a function getSocket()

put this method into application class so that we can access it anywhere and also then there will be single instance of mSocket throughout your application. Now whenever we require to start connection we just have to make a object of our application lets say MyApplication class is our application class extending Application. So to connect with socket the code will be

And the connection is established. If you want to disconnect the connection you just have to call the

And the connection breaks. You can use your emitters between this connection with both on and emit functions. And its done you are ready with your connection with your server.

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home