屏幕关闭一段时间后,Android断开了TCP连接

时间:2019-04-25 11:17:16

标签: android networking tcp

我正在应用程序中进行TCP客户端通信,该通信也应该在后台进行通信。我正在使用AsyncTask进行连接和接收数据,并使用带有Queue的其他线程进行发送。直到我让手机静置一会儿,它才能正常工作。大约5分钟后,连接断开。 ping手机运行正常。

我尝试了部分WakeLock,但是它什么也没做。

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) {

        }
    }

实际上发生了什么以及如何使其在后台连续工作?

0 个答案:

没有答案