我想实现一个方法来检查服务器是否仍然运行。我使用套接字在服务器和客户端之间进行通信。我的目标是向服务器打印换行符以测试它是否仍然运行,如果它不是IOException将被抛出,并且客户端将进入重新连接过程。客户端无限循环
我的问题是我停止终端服务器后,我的客户端进入无限循环打印“响应从服务器:”,当它不应该。
代码在客户端:
private static void readResponse() throws IOException{
String userInput;
try{
BufferedReader stdIn = new BufferedReader(new InputStreamReader(contentSocket.getInputStream()));
System.out.println("Response from server:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
} catch(IOException e) {
System.err.println("Something went wrong (5)");
}
}
private static void testConenction(Socket socket) throws IOException{
try{
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("\n");
writer.flush();
writer.close();
} catch(IOException e) {
System.err.println("Something went wrong (355)");
}
}
try{
//Connection stuff
while(true){
try{
testConenction(contentSocket);
readResponse();
} catch(IOException e) {
System.err.println("Something went wrong (327)");
closeSocket(contentSocket);
System.out.println("Trying to re-establish connection");
reconnect();
}
}
从技术上讲,没有用户输入,它与客户端的联合服务器 – zeelo 2014-09-12 13:00:44
我的错误,我应该更清楚,检查这个用户输入是否为空: private static void readResponse()throws IOException {userIQ; – 2014-09-12 13:01:11
我明白你的意思了,但是如果userInput是空的,我应该打异常(5)。 readResponse()主要功能是检索一个HTTP 200 – zeelo 2014-09-12 13:10:17