Java检测到客户端中的服务器断开连接

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

我创建了一个java-application,它有一个客户端和一个服务器端。双方通过套接字进行通信。这很有效,直到我的服务器应用程序被某些东西杀死,无法关闭或关闭serversocket。

客户端似乎没有注意到连接断开,只是在尝试读取下一个对象时挂起。

我还尝试每隔5秒从客户端发送一个测试对象,以检测服务器是否处于脱机状态,但这也不起作用。

我可能不得不提到这只发生在Windows上的服务器应用程序和Linux上的客户端(VirtualBox中的Ubuntu)上。 Windows-Windows工作正常。 Netstat甚至在Linux上给我一个ESTABLISHED,虽然我已经杀了服务器。

客户代码:

requestSocket = new Socket("192.168.1.3", 1234);
out = new ObjectOutputStream(new CipherOutputStream(requestSocket.getOutputStream(), ec));

in = new ObjectInputStream(new CipherInputStream(requestSocket.getInputStream(), dc));

new Thread() {
    public void run() {
        while(true) {
            try {
                out.writeObject(obj);
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("sent");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}.start();

服务器代码:

serverSocket = new ServerSocket(1234);
socket = serverSocket.accept();
out = new ObjectOutputStream(new CipherOutputStream(clientSocket.getOutputStream(), ec));
in = new ObjectInputStream(new CipherInputStream(clientSocket.getInputStream(), dc));

//do-while-reading on the socket[...]

我读了多个线程告诉我如何在服务器端检测丢失的连接,但没有找到客户端或答案对我不起作用。

java sockets cross-platform disconnect
2个回答
0
投票

在套接字上设置一个适当持续时间的读取超时,足以包括所有正常传输,并捕获SocketTimeoutException.


0
投票

问题似乎是VM。使用Manjaro Linux在我的笔记本电脑上进行测试时,一切都在开始时应该有效!

无论如何,谢谢你的贡献。 :)

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