Android: TCP client tutorial with TCP socket

The TCP client java class can be downloaded below.

This tutorial will give you some more insight into the code and will allow you to modify it to your own needs in less than 15 minutes! 

Using the TCP client class

 

Two important lines are these: 

The first line must contain the IP of your TCP server. The second line has to contain the port where it listens on for new connections.
public static final String SERVER_IP = “192.168.0.198”;
public static final int SERVER_PORT = 64000;

The sendMessage function:
It’s important to know that the sendMessage function always sends lines. This means that it will always end with a \n . So pay attention when you try to receive data from it, that you do not forget the \n .

The stopClient function is self explaining. It stops the connecting and sets the listener to null.

Now the real thing starts. The run() function.
The run() function starts a thread. TCP connection is not allowed to be in the same thread as the UI since it can block each other and you will get a list of Android errors (and you Android app will crash).

This “Socket socket = new Socket(serverAddr, SERVER_PORT);” will create a new socket with the right IP and PORT. This socket will be used to make connection with the server.

To be able to read and write we have to create a PrintWriter and BufferedReader as you can see in the code below. It creates two instances, one to read and one to write. It’s easy as that
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));

In this while loop, the thread reads the bufferreader until it has read a line or the buffer is full. If you want to send data piece by piece, you’ll have to add \n. The readLine() function will cut it off for you anyway! When the bufferreader has read something, it will call the messageReceived function. More information about it later in the tutorial!
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}

Here we create the messageReceived function. We declare the interface here but the function must be called in the mainactivity in an asynckTask doInBackground.
public interface OnMessageReceived {
public void messageReceived(String message);
}

 

In the mainactivitiy:

Place this line where you would like to start the tcp code.
new ConnectTask().execute("");

To stop, I advice you to use this:
if(TcpClient.isConnected)
{
mTcpClient.stopClient();
}

This is to prevent you to call the stopClient when the client is not yet created. This will cause your app to crash!

Now I will try to explain the asynck task. I advice you to download it below.

The task has 2 functions. messageReceived will be called if you receive a message.

In the messageReceived you see a call of publishProgress. This publishProgress function allows you to call the onProgressUpdate function.

The onProgressUpdate is an important one. It allows you to update your GUI without blocking your application!

In this onProgressUpdate you can use all of the GUI changing function, for example, a textview can be updated with it’s “setText(string)” function.

 

From now on you should be able to set it up all by yourself. If you have any more question, do not hesitate to leave a reply!

 

 

TCP client can be found here: TCP client

The asynck task:
public class ConnectTask extends AsyncTask {

@Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
//publishProgress(message);
Log.i("Debug","Input message: " + message);
}
});
mTcpClient.run();

return null;
}
}

@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.i("onProgressUpdate",values[0]);

}

Comments
  1. CAT says:

    Hello, thank you for the helpful advice this is a very nice tutorial. Can you please refresh you links i would like to see the code. Thanks

    • degoossez says:

      Hi, thank you for your feedback!
      I’ve searched for the files but they were gone, so I found the link posted above for the tcp client and added to code for a very simple async task and the onProgressUpdate. I hope it’s helpfull.

      Dries

  2. Is it possible to send JPEG images over tcp?

    • degoossez says:

      I think it is, or it should be. You’ll have to cut the image in pieces and send them in packages. Then receive them in packages and rewrite the file again.

  3. baretta says:

    Hi,
    very nice tutorial! i checked it and got problems by the asynctask if i want receive data from server. can you show me a little example how it works, thanks in advance.

    cheers,
    baretta

  4. Francois says:

    Hi! I was wondering if it was possible to alternate between a TCP and a http connection? My app controls 2 different devices, one through tcp and one through http. The problem is the tcp never reconnects after data is sent through http. They’re on two different asynctasks which are called through onclickListeners from two sets of directional buttons.

  5. sanket says:

    how to get data java server to android elumator.?

  6. md hussain says:

    hi thank for this tutorial but i stuck on point when connection with tcp server with my android client .
    i am successfully creating connection and sending my data to ip:port but i am not getting asynchronous response from .net server please suggest me for good implementation.

  7. Hi,

    Who the app’s coode call the onProgressUpdate function? I cant’t finde anythink calls to this function on you guthub code.

  8. ANUJ says:

    2 or more client can communicate parallel with server?

    • degoossez says:

      Hi Anuj, that depends on the server side. This is just one client that can connect to a server, to amount of clients a server can process fully depends on the server

  9. DRKIM says:

    thank you for the explain .I think i know why APP crashed .thanks a lot

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s