我正在使用 Oracle 的Knock Knock示例对服务器和客户端进行编程,当客户端连接到服务器时,它会收到一个要与之交互的 Knock Knock 笑话。一切运行良好。
我的问题是当客户端完成并与服务器断开连接时,服务器程序也会终止。如果服务器终止,我如何让它再次自动运行,以便它可以接受另一个客户端的请求,而无需手动重新启动服务器端?
下面是我的代码,其中注释显示了我卡在哪里。我正在使用两个在 vmware 播放器上运行的 centos vm。
import java.net.*;
import java.io.*;
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
server();
/*HERE IS WHERE I AM STUCK
* If I call server() above in my main method everything runs great.
* However, I would like to put a timer or something inside main so that
* every second it checks to see if server() is still running and if not
* then start it up again.
*/
}
public static void server() throws IOException{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}