Android Client server App with Windows PC using tethering

Many times we need to develop some application in android which can communicate with PC over USB connection. For these kind of development android has now exposed classes for making android phone as host or accessories but these api are working with andrino hardware. There is no driver form making PC as accessory.

So if you want to make some android application which should communicate with PC then you can do this by ADB(android debug bridge). You will find a lot of samples online for using ADB for making android phone as server or client for windows PC. But again this should be avoided.

Now all android phones are coming with feature USB tethering or wi-fi hot spot. Now on current windows OS tethering driver is inbuilt for android phone so you even don?t need to installing device drivers.

Just connect you phone using USB cable to PC and in phone enable USB tethering option and wait for internet connection establishment. Now you can see one network icon on windows system tray. You phone is now working as internet default gateway to your PC.

Now on windows check your network settings either using ipconfig command or using network settings dialog. Your PC default gateway IP is IP address of your phone.

Now your pc and android phone is connected over USB cable in tethering mode so you can do socket programming to make client server application on your phone and pc.

By using you programming logic you can know pc and phone IP address and you can run server socket any of device.

For example:

In Android service class you can make server listener using following code

private PrintWriter out = null;
private BufferedReader in = null;
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress(4040));
Socket client = null;
while((client = server.accept()) == null);
// Connected
enter code here
enter code here
out = new PrintWriter(new BufferedWriter(new 
OutputStreamWriter(client.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));

In above code I have created one server listener on 4040 port and when some incoming connection will come new socket instance should be created and using in and out streams you can read and write data.

On windows side you can make one Socket connection port 4040 and IP default gateway generated by phone.

In C# you can use TcpClient class to make connection with your phone.

Note: You can do same things on wi-fi hotspot also. Just you need to take care of default IP generated. On windows side you can easily read default getaway IP. Now you can make any type of application on android which you want to communicate with PC but you should know socket programming well.

Leave a Reply

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