Android TCP Client and Server Communication Programming–Illustrated with Example

This is a follow up post of the Android UDP Client and Server communication programming. TCP and UDP are the two main transport layer protocols used in today’s Internet. TCP aims to provide connection-oriented, reliable end-to-end communication service.

Similar to UDP, TCP programming in Android also uses  the APIs provided in java.net package.

To program a TCP server, one needs to create a ServerSocket instance, and listen to (call accept method) incoming connections. If there’s a connection established, accept method will return a socket representing the opened connection. One can then receive and send message through the socket. This is illustrated as the code below,

private void runTcpServer() {

    ServerSocket ss = null;

    try {

        ss = new ServerSocket(TCP_SERVER_PORT);

        //ss.setSoTimeout(10000);

        //accept connections

        Socket s = ss.accept();

        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

        //receive a message

        String incomingMsg = in.readLine() + System.getProperty("line.separator");

        Log.i("TcpServer", "received: " + incomingMsg);

        textDisplay.append("received: " + incomingMsg);

        //send a message

        String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");

        out.write(outgoingMsg);

        out.flush();

        Log.i("TcpServer", "sent: " + outgoingMsg);

        textDisplay.append("sent: " + outgoingMsg);

        //SystemClock.sleep(5000);

        s.close();

    } catch (InterruptedIOException e) {

        //if timeout occurs

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

        if (ss != null) {

            try {

                ss.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}

To program a TCP client, one needs to open a socket with server ip and port number. Once it’s connected, one can receive and send message through the socket. The code is as below,

private void runTcpClient() {

    try {

        Socket s = new Socket("localhost", TCP_SERVER_PORT);

        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

        //send output msg

        String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator"); 

        out.write(outMsg);

        out.flush();

        Log.i("TcpClient", "sent: " + outMsg);

        //accept server response

        String inMsg = in.readLine() + System.getProperty("line.separator");

        Log.i("TcpClient", "received: " + inMsg);

        //close connection

        s.close();

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    } 

}

Note that to use the network socket (ServerSocket and Socket, in our case), you’ll need to request for INTERNET permission. Adds the following line to AndroidManifest.xml will do,

<uses-permission android:name="android.permission.INTERNET"/>

Download and Screenshots
You can download the complete example (client) and (server) or from my github android tutorial repo. If you run server and client on your android device (server first), you’ll get something like this,

Untitled

Figure 1. Screenshot for TCP Communication Client and Server

The TCP server receives the TCP packet from TCP client and outputs the message to a TextView.

0 thoughts on “Android TCP Client and Server Communication Programming–Illustrated with Example”

  1. I’m wondering how to make an android device log in to a secure server via the web. I wish to do this using an android application. The setup would be much like the FaceBook app. Please advise.

  2. Hey, great tutorial. Thank you very much. I had a question, why wouldnt it work when I run the server from one android device and the client from another android device?

    It does work when I run both from same android phone.

    thanks in advance

    1. Hi, (sorry for my bad english) to run the server from one android device and the client from another android device you must make few change
      1. change the string “localhost” with “10.0.2.2” in the client and set client TCP_SERVER_PORT = 5000 in both classes;
      2. set server TCP_SERVER_PORT = 6000;
      3.now go to the host machine terminal and write
      >>telnet localhost 5554
      >>redir add tcp:5000:6000
      I tried and it works!
      I took a cue from this link http://stackoverflow.com/questions/4683854/connecting-2-emulator-instances-in-android and I combined the examples :-)

  3. Great tutorial.

    How to update the code so that the server and client continue working like chat back and forth instead of closing just only after one message?

  4. I am doing some socket programming on Android as well. But I having problem when I try to run client and server on different machine. It seems like Android emulator cannot get any message but it is fine to send out message.

    Have you try client/server on different machine before? If yes, how to you make the Android receive message?

  5. My TcpServer programme is suddenly stopping at ss = new ServerSocket(TCP_SERVER_PORT);(found through display.settest statements)
    Can you pls help me out?

  6. i had run this code but i had got the IOException. Also note that Socket had not been created though INTERNET permission has been set.

  7. Thanks a lot……. ur efforts really helped… n must be helpin millions…….
    i tried it to communicate between a phone and a virtual android machine and it worked very well.

  8. I’m getting a networkOnMainThread exception. I can’t do these network communications on the same thread as my main android application.
    Could you make an example where this communication runs on an Asynctask?

    Thanks

Leave a Reply

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