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.

 

26 Responses to Android TCP Client and Server Communication Programming–Illustrated with Example

  1. kajal says:

    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.

  2. Mayank Arora says:

    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.

  3. adrian says:

    Same error: IOException …

  4. Anonymous says:

    that is not working on client.

  5. dave says:

    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

  6. Ian says:

    After a period of time with no activity the connection closes – how can I keep it going?

  7. Sh says:

    Thanks for the projects it works and very helpful

Leave a Reply

Your email address will not be published.

* Copy This Password *

* Type Or Paste Password Here *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.