I need a way to automatically close the server program which runs by using some sort of timer. Till now this is what I got
long start = System.currentTimeMillis();
long end = start + 10 * 1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
count = count + 1;
}
welcomeSocket.close();
Is this possible? Please help and don’t down vote. I’m kinda a noob regarding client- server in Java.
You can use setSoTimeout for that.
Typically, you’ll set that with some value like 100 ms, enter a loop and call accept. When the timeout exception is thrown you’ll check to see if its ok to exit or not and either fall out of the loop or keep going.
Then make sure you clean up the socket when you’re done.