는 방법을 감지하는 원격 측 소켓 가까?[중복]
-
02-07-2019 - |
문제
이 질문은 이미 있는 대답을 여기:
당신은 어떻게 검출하는 경우 Socket#close()
는 소켓 원격 측면?
해결책
이 isConnected
방법은 도움이 되지 않습니다,그것은이 돌아 true
는 경우에도 원격 측면이 닫힌 소켓에.이것을 보십시오:
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
서버를 시작하고,시작하는 클라이언트입니다.당신이 볼 수는 그것을 인쇄하"연결되어 있:true"두 번지만,소켓이 닫히는 두 번째입니다.
유일한 방법은 정말 찾아내를 읽고(당신을 얻을 것으로-1 을 반환 값)또는 쓰기(는 IOException
(broken pipe)가 발생)에 관련된 입력/OutputStreams.
다른 팁
이후 답변을 벗어나기로 결정했을 테스트하는이 게시한 결과를 포함한 테스트를 예입니다.
서버가 여기에 쓰는 데이터는 클라이언트와 기대하지 않는 모든 입력이 있습니다.
서버:
ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
out.println("output");
if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
System.out.println(clientSocket.isConnected());
System.out.println(clientSocket.getInputStream().read());
// thread sleep ...
// break condition , close sockets and the like ...
}
- clientSocket.isConnected()반환 항상 진실하면 클라이언트가 연결(고 후에도 연결 끊기)이상!!
- getInputStream().read()
- 실 기다려 입력으로 클라이언트가 연결되어 있고 따라서 귀하의 프로그램으로 아무것도하지 않습-는 경우를 제외하고 당신은 몇 가지 입력
- -1 을 반환합니다면 클라이언트 연결이 끊어
- 니다.checkError()은 진정한 한 빨리의 클라이언트 연결이 끊어 그래서 내가 추천
당신은 또한 확인할 수 있는 소켓을 출력 스트림에 오류가 쓰는 동안 클라이언트 소켓에.
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
방법 Socket.사용할 수 있는 즉시를 던져 SocketException 경우 remote 시스템에 연결/연결을 닫았습니다.
제휴하지 않습니다 StackOverflow