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,

privatevoid 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()));

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 ScreenshotsYou 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,

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.

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?