G.V. G.V. - 1 year ago 331
Android Question

Really simple TCP client

I want with my app to enter in the url of my server e.g.
and the port e.g.
When my server receives the TCP Request message, it sends back a file (the server is already implemented).

I think that I don't need something complicated like an AsyncTask, as I do not want to keep the connection. Receiving the answer from the server, my connection must be closed.

Any indication for a way forward or a tip is highly appreciated.

Answer Source

Here is a simple TCP client that uses Sockets that I got working based on code in this tutorial (the code for the tutorial can also be found in this GitHub repository).

Note that this code is geared to sending strings back and forth between the client and server, usually in JSON format.

Here is the TCP client code:

public class TcpClient {

    public static final String SERVER_IP = ""; //your computer IP address
    public static final int SERVER_PORT = 1234;
    // message to send to the server
    private String mServerMessage;
    // sends message received notifications
    private OnMessageReceived mMessageListener = null;
    // while this is true, the server will continue running
    private boolean mRun = false;
    // used to send messages
    private PrintWriter mBufferOut;
    // used to read messages from the server
    private BufferedReader mBufferIn;

     * Constructor of the class. OnMessagedReceived listens for the messages received from server
    public TcpClient(OnMessageReceived listener) {
        mMessageListener = listener;

     * Sends the message entered by client to the server
     * @param message text entered by client
    public void sendMessage(String message) {
        if (mBufferOut != null && !mBufferOut.checkError()) {

     * Close the connection and release the members
    public void stopClient() {

        mRun = false;

        if (mBufferOut != null) {

        mMessageListener = null;
        mBufferIn = null;
        mBufferOut = null;
        mServerMessage = null;

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVER_PORT);

            try {

                //sends the message to the server
                mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                //receives the message which the server sends back
                mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {

                    mServerMessage = mBufferIn.readLine();

                    if (mServerMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class


                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");

            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);



    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);


Then, declare a TcpClient as a member variable in your Activity:

public class MainActivity extends Activity {

    TcpClient mTcpClient;


Then, use an AsyncTask for connecting to your server and receiving responses on the UI thread (Note that messages received from the server are handled in the onProgressUpdate() method override in the AsyncTask):

public class ConnectTask extends AsyncTask<String, String, TcpClient> {

    protected TcpClient doInBackground(String... message) {

        //we create a TCPClient object
        mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
            //here the messageReceived method is implemented
            public void messageReceived(String message) {
                //this method calls the onProgressUpdate

        return null;

    protected void onProgressUpdate(String... values) {
        //response received from server
        Log.d("test", "response " + values[0]);
        //process server response here....


To start the connection to your server, execute the AsyncTask:

new ConnectTask().execute("");

Then, sending a message to the server:

//sends the message to the server
if (mTcpClient != null) {

You can close the connection to the server at any time:

if (mTcpClient != null) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download