1

I'm doing a TCP client communication in my application that should communicate in background also. I'm using AsyncTask for connection and receive data and different Thread with Queue for send. It's work fine until I let the phone alone for a while. After about a 5 minutes connection losed. Ping the phone is going well.

I've tried a partial WakeLock but it does nothing.

TcpClient


public class TcpClient {
    public static final String TAG = TcpClient.class.getSimpleName();
    public static final String SERVER_IP = "192.168.0.1"; //server IP address
    public static final int SERVER_PORT = 666;
    // message to send to the server
    private String mServerMessage;
    // sends message received notifications
    private OnMessageReceived mMessageListener = null;
    private OnConnectionEstablished mConnectionEstablishedListener = 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;
    private BlockingQueue<String> mSendQueue;
    private Thread mSendingThread;

    /**
     * Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TcpClient(OnMessageReceived listener) {
        mMessageListener = listener;
        mSendQueue = new LinkedTransferQueue<String>();
    }

    public void setOnConnectionEstablished(OnConnectionEstablished listener) {
        mConnectionEstablishedListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     *
     * @param message text entered by client
     */
    public void sendMessage(final String message) {
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                if (mBufferOut != null) {
//                    Log.d(TAG, "Sending: " + message);
//                    mBufferOut.println(message);
//                    mBufferOut.flush();
//                }
//            }
//        };
//        Thread thread = new Thread(runnable);
//        thread.start();
        try {
            mSendQueue.put(message);
        } catch (InterruptedException e) {

        }
    }

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

        mRun = false;

    }

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

            Log.d("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()));

                mSendingThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Boolean running = true;
                        while (running) {
                            try {
                                String msg = TcpClient.this.mSendQueue.take();
                                Log.d(TAG, "Sending: " + msg);
                                mBufferOut.println(msg);
                                mBufferOut.flush();
                            } catch (InterruptedException e) {
                                running = false;
                                Log.d(TAG, "Stop seinding process");
                            }
                        }
                    }
                });
                mSendingThread.start();

                if(mConnectionEstablishedListener != null) {
                    Log.d("TCP Client", "C: Connection established");
                    mConnectionEstablishedListener.connectionEstablished(true);
                }


                //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
                        mMessageListener.messageReceived(mServerMessage);
                    }

                }

                Log.d("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.
                socket.close();
                if(mConnectionEstablishedListener != null) {
                    mConnectionEstablishedListener.connectionEstablished(false);
                }
            }

        } catch (Exception e) {
            Log.e("TCP", "C: Error", e);
            if(mConnectionEstablishedListener != null) {
                mConnectionEstablishedListener.connectionEstablished(false);
            }
        }
        mSendingThread.interrupt();
        if (mBufferOut != null) {
            mBufferOut.flush();
            mBufferOut.close();
        }

        mMessageListener = null;
        mConnectionEstablishedListener = null;
        mBufferIn = null;
        mBufferOut = null;
        mServerMessage = null;
    }

    public interface OnConnectionEstablished {
        public void connectionEstablished (Boolean established);
    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the Activity
    //class at on AsyncTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
        @Override
        protected TcpClient doInBackground(String... message) {
            PumpApplication.this.client = new TcpClient(new TcpClient.OnMessageReceived() {
                @Override
                public void messageReceived(String message) {
                    if(PumpApplication.this.mMessageReceivedListener != null) {
                        PumpApplication.this.mMessageReceivedListener.messageReceived(message);
                    }
                }
            });
            PumpApplication.this.client.setOnConnectionEstablished(new TcpClient.OnConnectionEstablished() {
                @Override
                public void connectionEstablished(Boolean established) {
                    if(PumpApplication.this.mConnectionEstablishedListener != null)
                        PumpApplication.this.mConnectionEstablishedListener.connectionEstablished(established);
                }
            });
            PumpApplication.this.client.run();
            return null;
        }
        @Override
        protected void onProgressUpdate(String... values) {

        }
    }

What is actually happening and how to get it work in background continuously?

idsoft
  • 11
  • 2
  • which device you are using? – Ganesh Pokale Apr 25 '19 at 11:19
  • Last time it was galaxy a20, but behaviour is the same on xiaomi redmi 4x. Also I saw if run app with debugger connected it doesnt lose the connection. – idsoft Apr 25 '19 at 12:52
  • Go to settings> Battery optimization > select your app > and click don't optimized/ auto launch if this solve your problem then you need to use this code for same redirection For sure this is your answer https://stackoverflow.com/a/55828769/3522570 – Ganesh Pokale Apr 25 '19 at 13:46
  • Thank you, this is helped! It's is quite not obvious to make it on samsung, but it worked after all. – idsoft Apr 25 '19 at 15:54

0 Answers0