远程应用程序强制关闭后,检测套接字关闭 [英] Detect Socket is closed after remote application is closed forcibly

查看:118
本文介绍了远程应用程序强制关闭后,检测套接字关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java套接字方面遇到了一些麻烦。
我有一对在它们之间建立连接的应用程序(一个打开 ServerSocket ,调用 accept()并等待,另一个通过 Socket(InetAddress,int)构造函数连接。

I'm having some trouble with Java Sockets. I have a pair of applications that establish a connection between them (one opens a ServerSocket, calls accept() and waits, and the other connects via the Socket(InetAddress,int) constructor.

套接字后建立连接后,使用此 Runnable 创建线程

After the socket connection is established, a Thread is created with this Runnable.

 public void run() {    
    System.out.print("Watching Socket for closing ");
    while(running) {
        if(socket.isClosed()) {
            System.out.println("Socket has been closed");
            break;
        }
    }
    this.running = false;
    //safely ends this application by closing i/o and exiting.
}

我的问题是,当其中一个应用程序意外关闭时(在我的情况下从Eclipse终止)调用 Socket.isClosed()仍然显示套接字已打开,所以循环继续运行好像Socket是打开的。

My problem is that when one of the applications is closed unexpectedly (in my case terminated from Eclipse) calling Socket.isClosed() still shows the socket is open, and so the loop keeps running as if the Socket was open.

当另一侧的Java应用程序被强制结束时,如何检测Socket何时关闭?

How can I detect when the Socket is closed when the Java application on the other side is forcibly ended?

推荐答案

socket.isClosed()返回true的唯一方法就是你自己打电话 socket.close()因为它是布尔值设置为 true 的唯一部分。

The only way that socket.isClosed() return true is if you call yourself socket.close() as it is the only part where the boolean will be set to true.

你可以做的只是尝试使用 inputStream <读取套接字如果它已关闭(如果已到达流的末尾),将返回/ code>和-1。

What you could do is simply try to read from the socket using an inputStream and -1 will be returned if it is closed (if the end of stream has been reached).

参见文档以获取更多信息。

这篇关于远程应用程序强制关闭后,检测套接字关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆