I have to write java codes implementing the TCP server & TCP client with a 10% of transmission failure determined by a random number. Now in the receiver side it needs to wait for 2000 ms(2 sec.) & if no data received from the sender in this 2 sec. then it will stop waiting for data from the sender & send back a negative ACK to the sender.
BufferedReader inFromSender =new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
long startTime = System.currentTimeMillis();
while(( System.currentTimeMillis() - startTime) < 2000 )
{
clientSentence = inFromSender.readLine();
System.out.println("Received: " + clientSentence);
}
System.out.println("Data Transmission failed");
But once the while loop begins & the receiver goes in to read from the sender, it never breaks.. even if the 2 sec. timeout is over. How can I abort/stop the receiver from waiting for sender data after 2 sec (timeout).
One way to go would be to have a
Threadthat would close the socket when the timeout is reached. This would make theread(...)call fail (probably anIOException) and therefore you would go out from the loop.Example: