有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android TCPsocket在应用程序关闭时不会断开连接

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

那么我到底做错了什么?我是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) 个答案

  1. # 1 楼答案

    更准确的说法是,您没有正确地测试断开连接

    1. ^当对等方断开连接时,{}不会神奇地变为真。所以用它来控制读循环是徒劳的。它只会告诉你是否关闭了这个插座
    2. ^当对等方断开连接时,{}返回null,但您将其视为另一个值

    使用readLine()的正确循环如下所示:

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