Monday 16 February 2015

Socket Programming With Android Part 1

Hi Friends, this is my first blog on android. And  I have found out that there is so much less information about Socket Programming with Android. So basically I am not a theoretical so  i would prefer practical. So here in part 1 of socket programming i will cover following topics.
1)What is Socket Programming?
2)set up Node.js. 
3)Android Socket Programming.

What is Socket Programming?
Its provides a Communication medium between two clients. The server that provides the medium is know as node.js. For example in chatapp between two clients node.js server acts as socket programmer.

Set Up Node.js
In Ubuntu it will be installed as in following steps in command terminal
sudo apt-get install python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
Now socket setup for android to connect to socket server.

Android Socket Programming
To have to connect to server from Android you might have to create a socketio.jar file.
I have used following https://github.com/Gottox/socket.io-java-client library to create jar file. And I am also uploading the socketio.jar file so please download it from here and paste it in your libs folder.
So now to check connection from android you might have to create a socket file that will work as Server
So socket file will work after installing node in your Computer. So here is the server.js file 

var io  = require('socket.io');  
var server = io.listen(4732);

var macbook_socket = undefined;

server.sockets.on('connection', function(socket) {  
var ipAddress = socket.handshake.address.address;
    socket.emit('helo', {msg: 'welcome'});
    socket.on('user', function(data) {
        if (data.type == "client") {
            //saving socket
            macbook_socket = socket;
        }
    });
});
To start server you will have to type node yourfilename.js
I have also uploaded the whole file with package.json in that folder download it from here.
In above server.js file we will start the server from terminal like the following screenshot. If everything goes well you will get below screenshot.

Now the next important step on how to connect android with this server. I think it's too much for now. Next we will continue in part 2 of socket programming. Till then stay tuned. If you find it useful then comment or mail me.

Download links:


If any issues contact or you can comment it here.
mehdisunasara@gmail.com