I am using TCP in my application. I am facing data loss issue if even if close socket gracefully. Here is the two sample program to replicate scenario.
//TCP Sender program continuously sends data
public class TCPClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket soc = new Socket("xx.xx.xx.xx",9999);
OutputStream stream = soc.getOutputStream();
int i=1 ;
while(true) {
System.out.println("Writing "+ i);
stream.write(i++);
stream.flush();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
// TCP Server/Receiver
public class TCPServer2 {
public static void main(String[] args) throws IOException {
System.out.println("program started");
ServerSocket serverSock = new ServerSocket(9999);
Socket socket =serverSock.accept();
System.out.println("client connected");
InputStream stream = socket.getInputStream();
InputStreamReader reader = null;
reader = new InputStreamReader(stream);
socket.setTcpNoDelay(true);
int n=0;
int i=1;
while (true) {
try {
n = reader.read();
System.out.println("Msg No.: "+n);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
break;
}
if(i==5) {
System.out.println("closing socket");
socket.close();
//client should get exception while sending 6th msg
break;
}i++;
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
}
}
Now Ideally TCPClient program should get exception while sending 6th message but it gets Exception while sending 7th message. Is there any way to avoid this data loss problem apart from using high level protocols and SO_LINGER(linger does helps in this program but it may cause data loss issue in several other scenarios)?
NB: This message loss issue occurs if we use two different windows machine. On the same machine it works fine.