如何关闭锁定在无限循环中的套接字?

问题描述 投票:1回答:1

我创建了一个服务器 - 客户端项目,服务器在该项目中继续监听并打印信息。但是,当我关闭客户端时,服务器保持打开状态。问题是我需要将其插入到另一个应用程序中,并且,如果服务器最初没有关闭,则应用程序将不会打开,除非我终止该端口中的进程(但这不是我的选项)。一旦客户端断开连接,我该怎么做才能正确关闭服务器?

这是代码:

服务器:

public class Server {

    public static void main(String[] args) {
        Connection conn = new Connection();
        new Thread(conn).start();
    }

    private static class Connection implements Runnable {
        @Override
        public void run() {
            try (ServerSocket serverSocket = new ServerSocket(5005)) {
                Socket socket = serverSocket.accept();

                listener(socket);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        private void listener(Socket socket) throws IOException {
            DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
            DataInputStream inputStream = new DataInputStream(socket.getInputStream());
            boolean alive = true;

            while (alive) {
                try {
                    outputStream.writeUTF(new Scanner(System.in).nextLine());
                    System.out.println(inputStream.readUTF());
                } catch (IOException ex) {
                    ex.printStackTrace();
                    alive = false;
                }
            }
        }
    }
}

客户:

public class Client {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 5005)) {
            DataInputStream inputStream = new DataInputStream(socket.getInputStream());
            DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());

            while (socket.isConnected()) {
                System.out.println("Incoming data: " + inputStream.readUTF());

                outputStream.writeUTF(new Scanner(System.in).nextLine());
                outputStream.flush();
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

从现在开始,非常感谢!

java multithreading sockets
1个回答
0
投票

强制系统等待而不是关闭的东西就是Server.java上的这一行:

outputStream.writeUTF(new Scanner(System.in).nextLine());

一旦它开始等待用户输入,它会在实例的生命周期内永远等待,尽管您的客户端已断开连接。

那么你能做什么?您可以创建另一个线程,使其定期生成“ENTER”输入(如果您坚持使用新的Scanner(System.in)),例如每5秒输入一次。在输入或任何其他有意义的输入之后,如果您认为这不是来自客户端,请不要将其写入客户端并再次等待用户输入(如果您的客户端仍然连接!)。如果您的客户端未连接,请完成循环。

请检查Java Robot类和this example

© www.soinside.com 2019 - 2024. All rights reserved.