Android TCP - 应用程序关闭时Socket不会断开连接

时间:2015-08-07 01:22:32

标签: java android sockets tcp

我正在尝试将TCP与Android应用程序一起使用,因此有两个项目,一个是服务器,另一个是客户端。 当我运行服务器并打开客户端时,一切正常并且消息正在传递给双方,但是当我关闭应用程序(从模拟器)时,它不会在控制台中提醒我套接字连接已关闭且尝试获取另一个连接,以便在尝试重新打开应用程序时,它不会重新连接,也不会传递消息。

那我在这里做错了什么?我是Android和TCP的新手,所以如果这是一个非常新的问题,我很抱歉。

@Override
public void run() {
    super.run();

    running = true;

    try {
        System.out.println("S: Connecting...");

        //create a server socket. A server socket waits for requests to come in over the network.
        ServerSocket serverSocket = new ServerSocket(SERVERPORT);

        //create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
        while (running) {
            Socket client = serverSocket.accept();

            try {

                //sends the message to the client
                mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

                //read the message received from client
                BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

                //in this while we wait to receive messages from client (it's an infinite loop)
                //this while it's like a listener for messages
                while(!client.isClosed()) {
                    String message = in.readLine();
                    if (message != null && messageListener != null) {
                        //call the method messageReceived from ServerBoard class
                        messageListener.messageReceived(message);
                    }
                }


            } catch (Exception e) {
                System.out.println("S: Error");
                e.printStackTrace();
            } finally {
                client.close();
                System.out.println("S: Done.");
            }
      }

    } catch (Exception e) {
        System.out.println("S: Error");
        e.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:2)

It would be more accurate to say that you aren't testing for disconnection correctly.

  1. Socket.isClosed() does not magically become true when the peer disconnects. So using it to control a read loop is futile. It only tells you whether you have closed this socket.
  2. readLine() returns null when the peer has disconnected, but you're treating it as just another value.

A correct loop using readLine() looks like this:

while ((line = in.readLine()) != null)
{
    // ...
}