MyAd

Wednesday 18 October 2017

Send data from Android to PC using TCP Sockets in Android Studio

So guys in this blog you will get the source code of how to send data from Android to PC using Sockets.


So first of all, the first step is to create a project and then create an activity. After that you have to modify your xml file so that it is able to take message input from the user.


First of all you must know the concepts about Sockets.
A socket is an end point of a two way communication between two computer programs running on a network. 
A socket contains two things. An ip address and the Port number.
So in Java we can initialize a socket like:

Socket s = new Socket("ip","port");


So basically we have a socket which communicates with a ServerSocket running on other network. After initializing socket, we need to write data to it through the class PrintWriter.
We can also use OutputDataStream to send the data either in the form of a string or in bytes.


So in our project we will create a separate class which inherits AsyncTask class.




So in this class we are connecting to the Server which contains the server socket running at port number 6000. So now our socket will try to connect with the server socket in that ip address. If it connects, write the data to it through PrintWriter class.

After that you need to modify your MainActivity.java file like this:




So finally you need to add the INTERNET permission in your Manifest file.
The AsyncTask enables the developers to use the UI thread properly and easily. 
This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

NETBEANS (SERVER code)



So you have to create a new project in netbeans or eclipse. After that you have to create a java file (jFrame) with a main method.




In your java project, you need to initialize the ServerSocket with its IP Address. After that you need to use the BufferedReader class and InputStreamReader streams to get the Data from the client.  So thats all. In this way you will be able to send data (messages) from Android to Your PC.

Things to Remember:


Make sure you are connected to the same Wifi router.

No comments:

Post a Comment

Decompile any APK to get Source Code

In this video I will teach you how to compile any APK file to decompile and get the source code of any android app using Android Studio....