participate


Socket Programming - TCP client application does not detect network failure
<<   Back to Forum  |   Give us Feedback
This topic has 45 replies on 4 pages.    1 | 2 | 3 | 4 | Next »
Olivier_Merigon
Posts:2
Registered: 7/19/04
TCP client application does not detect network failure   
Jul 19, 2004 5:22 AM

 
Hi,

This is a behavior of the TCP socket in Java I dont' understand:.
Let say we have a simple client/server application running on TWO different
machines.
The client send bytes to the server.
The server recieved the bytes and wait for about X sec.
During this waiting time, we disconnect the server from the network (just by
unplugging the server network cable).
After the waiting time the server is aware of the network failure (a
SocketException is thrown : connection reset, because it is trying to send
the response)
But on the client side it is still stuck on a "rcv =
commandInput.readLine();" statement (see after for the complete code), it
will never be aware of the network failure !!! Even after one hour the
client is still waiting to read something on a closed socket. Is this the
normal behavior ?

In reality we are dealing with an application that use the FTP server to
server mode (we are controlling only the command socket, the data transfer
is made by the servers). We have to transfer huge files, thus we can not set
up a time out. If the last scenario occurs, some of our transfers are stuck
and it is not possible for us to detect the failure. The client will wait
for ever the response.

Does anybody have already deal with that ?

Below is the simple client and server I made in order to make my experiment.
The client just read the keyboard input and send it to the server; the
server just echo the request except if the request
is 'wait X', in this case it will wait for X sec before responding.

Thanks by advance,

Olivier MERIGON


CLIENT:


package com.iratensolutions.test.ftp;
 
import java.io.BufferedReader;
 
import java.io.IOException;
 
import java.io.InputStreamReader;
 
import java.io.OutputStreamWriter;
 
import java.io.PrintWriter;
 
import java.net.Socket;
 
/**

* A Client/Server application to test the network failure behavior with TCP.

* This the client part. It just sends the keyboard input to the server.

* @author Olivier MERIGON

*/
 
public class TestNetworkFailureClient {
 
public static void main(String[] args) {
 
 
if (args.length != 1) {
 
System.out.println("usage: java
com.iratensolutions.test.ftp.TestNetworkFailureClient serverAdress");
 
}
 
 
Socket commandSocket = null;
 
BufferedReader commandInput;
 
BufferedReader keyboardInput;
 
PrintWriter commandOutput;
 
try {
 
 
commandSocket = new Socket(args[0], 666);
 
commandInput = new BufferedReader(new
InputStreamReader(commandSocket.getInputStream()));
 
keyboardInput = new BufferedReader(new InputStreamReader(System.in));
 
commandOutput = new PrintWriter(new
OutputStreamWriter(commandSocket.getOutputStream()));
 
} catch (Exception e) {
 
e.printStackTrace();
 
return;
 
}
 
 
System.out.println("CLIENT STARTED");
 
String snd;
 
String rcv = null;
 
try {
 
do {
 
System.out.print("KEYBOARD: ");
 
snd = keyboardInput.readLine();
 
if (snd != null) {
 
commandOutput.println(snd);
 
commandOutput.flush();
 
System.out.println("SND: " + snd);
 
rcv = commandInput.readLine();
 
System.out.println("RCV: " + rcv);
 
}
 
} while (rcv != null);
 
} catch (IOException e1) {
 
e1.printStackTrace();
 
}
 
}
 
}
 




SERVER


package com.iratensolutions.test.ftp;
 
import java.io.DataInputStream;
 
import java.io.IOException;
 
import java.io.PrintStream;
 
import java.net.ServerSocket;
 
import java.net.Socket;
 
/**

* A Client/Server application to test the network failure behavior with TCP.

* This the server part. The server can wait X second after responding to a
request.

* If a wait request is received, the server just answer the time waited
after

* the requested wait time, otherwise it respond immediatly the request
number.

* usage: wait intNbSec | any text

* @author Olivier MERIGON

*/
 
public class TestNetworkFailureServer {
 
public static void main(String args[]) {
 
ServerSocket echoServer = null;
 
String line;
 
DataInputStream is;
 
PrintStream os;
 
Socket clientSocket = null;
 
try {
 
echoServer = new ServerSocket(666);
 
System.out.println("SERVER STARTED");
 
} catch (IOException e) {
 
System.out.println(e);
 
}
 
while (true) {
 
try {
 
clientSocket = echoServer.accept();
 
System.out.println("Handling new client...");
 
is = new DataInputStream(clientSocket.getInputStream());
 
os = new PrintStream(clientSocket.getOutputStream());
 
int loopId = 0;
 
do {
 
line = is.readLine();
 
System.out.println("RCV: " + line);
 
//Handle "Wait" command
 
if (line.trim().startsWith("wait")) {
 
String[] tab = line.split("\\s");
 
boolean ok = false;
 
try {
 
int nbSec = Integer.parseInt(tab[1]);
 
System.out.println("...waiting for " + nbSec + " sec.");
 
try {
 
Thread.sleep(nbSec * 1000);
 
} catch (InterruptedException e1) {
 
}
 
String resp = "...end of wainting periode of " + nbSec + " sec.";
 
os.println(resp);
 
System.out.println("SND: " + resp);
 
ok = true;
 
} catch (Exception e) {
 
ok = false;
 
}
 
if (!ok) {
 
String resp = "usage: wait intNbSec | any text";
 
os.println(resp);
 
System.out.println("SND: " + resp);
 
}
 
//Handle "normal" action
 
} else {
 
os.println("# " + loopId);
 
System.out.println("SND: # " + loopId);
 
}
 
loopId++;
 
} while (line != null);
 
} catch (IOException e) {
 
System.out.println(e);
 
}
 
}
 
}
 
}
 
eduar09
Posts:75
Registered: 10/9/99
Re: TCP client application does not detect network failure   
Jul 19, 2004 7:03 AM (reply 1 of 45)  (In reply to original post )

 
That is completely normal TCP behaviour. TCP/IP does NOT normally send keep alive message on the line by design. So there is not way for the client to know the server is unreachable. It is therefore left up to the protocol to handle this.

There are several ways to do this.
1) Use setKeepAlive(). This will turn on TCP/IPs Keep Alive mechanism. This will ensure the socket is still alive by sending a message every 2 hours.
2) Ensure that each side of the connection sends data periodically, then setSoTimeout() to a reasonable value. So if you ping every 2 minutes.. set SoTimeout to 3 minutes. This will cause a read() to unblock with an exception if no data is received in the alloted time.
 
kajbj
Posts:28,981
Registered: 3/21/00
Re: TCP client application does not detect network failure   
Jul 19, 2004 11:57 AM (reply 2 of 45)  (In reply to original post )

 
Hi,

Or implement it using NIO. In nio you gets notifications when the connection is down/closed.

/Kaj
 
pkwooster
Posts:4,221
Registered: 05/10/01
Re: TCP client application does not detect network failure   
Jul 19, 2004 5:45 PM (reply 3 of 45)  (In reply to #2 )

 
NIO really doesn't help in this case. The problem isn't with Java socket support, it in the definition of TCP. The intent of TCP was to provide what was called "full reconnect" back int he elder days. The idea was that if a network connection was disconnected the protocol would attempt to find another route for the data. For this reason TCP is reluctant to inform a user that the connection has been lost. If you try to send on a lost connection, you will see a exception that says that the connection has been terminated.

I just tested this with a NIO client and a Stream client on W2K and a NIO server on Solaris9. And none of them saw the removal of the lan connection from the Solaris box. Removing the lan connection from the W2K box informed the clients that the socket had been "forcibly closed".

The only way to be certain that a connection is actually up is to send a message and get a response. If you can't build this into your protocol you will need to use an additional connection, or try to get a response from port 7 or some other cooperative port. This won't say that your connection is up, but it will show when a partner goes silent.
 
kajbj
Posts:28,981
Registered: 3/21/00
Re: TCP client application does not detect network failure   
Jul 19, 2004 11:27 PM (reply 4 of 45)  (In reply to #3 )

 
Hi,

Interesting I had only tried it on Win 2k and XP, and they gave me information on the disconnects. I thought unix did the same.

/Kaj
 
subSequence
Posts:122
Registered: 5/24/04
Re: TCP client application does not detect network failure   
Jul 20, 2004 1:02 AM (reply 5 of 45)  (In reply to #4 )

 
The only reliable way to check that a Java Socket is alive is to send bytes down the stream I'm afraid.
 
K.Mariya
Posts:7
Registered: 4/23/04
Re: TCP client application does not detect network failure   
Jul 30, 2004 5:56 PM (reply 6 of 45)  (In reply to original post )

 
hi all..


I am also getting same problem in my application. TCP Server is running remote PC and client PC connected to serevr, after connection eastiablished I pullout the Network work cable from client PC. But serevr deos not aware of that client connection status. At server side I send a message to that client every 10 seconds once. There is NO ERROR while sending message to client after client disconned from network.

As per TCP protocol specification, when you send a message to client it will esure that message is reached or not (handshaking). But here seems like its not happening like that.

If any one know the answer plese let me know

Thanks in adavance
Mariya
 
jschell
Posts:38,148
Registered: 11/3/97
Re: TCP client application does not detect network failure   
Aug 2, 2004 11:35 AM (reply 7 of 45)  (In reply to #6 )

 
hi all..


I am also getting same problem in my application. TCP
Server is running remote PC and client PC connected to
serevr, after connection eastiablished I pullout the
Network work cable from client PC. But serevr deos not
aware of that client connection status. At server side
I send a message to that client every 10 seconds once.
There is NO ERROR while sending message to client
after client disconned from network.

Either you are not using TCP or you have done something else to either hide or disable that feature. And I only say disable because conceivably you could set the write timeout to a very high value. You could be hiding it by catching an exception and then throwing it away.

A write timeout will normally take minutes. So if you don't wait long enough you won't see the failure.
 
Cipson_here
Posts:5
Registered: 3/8/04
Re: TCP client application does not detect network failure   
Aug 4, 2004 2:24 AM (reply 8 of 45)  (In reply to #7 )

 
Im also facing the same problem? I want to check the availability of network using isConnected().. but it gives a totally negative answer.

Im attaching my client and server program.
On client end : after making connection, the main thread will sleep for 10 seconds, meanwhile I removed the network cable, but the isConnected() and isBound() methods returns true?

Is there any solution for this problem? Or sun just kidding developers?

import java.net.;
import java.io.
;

class JavaServer
{
public static void main(String args[]) throws Exception
{
ServerSocket server = new ServerSocket(7777);
Socket socket = server.accept();
while(true){
Thread.sleep(100);
}
}
}


import java.net.;
import java.io.
;

class JavaClient
{
public static void main(String args[]) throws Exception
{
Socket socket = new Socket("10.200.209.47",7777);
System.out.println("Connected "+socket.isConnected());
System.out.println("Connected "+socket.isBound());
Thread.sleep(10000);
System.out.println("Connected "+socket.isConnected());
System.out.println("Connected "+socket.isBound());
}
}
 
subSequence
Posts:122
Registered: 5/24/04
Re: TCP client application does not detect network failure   
Aug 4, 2004 3:50 AM (reply 9 of 45)  (In reply to #8 )

 
You have to use SocketChannel.read or SocketInputStream.read
They will return -1 if not connected.
 
ggainey
Posts:1,910
Registered: 23/08/97
Re: TCP client application does not detect network failure   
Aug 4, 2004 5:45 AM (reply 10 of 45)  (In reply to #8 )

 
<rant>
Doesn't anybody read the damn docs anymore?

isBound() Returns: true if the socket successfuly bound to an address[/i]

isConnected() Returns: true if the socket successfuly connected to a server

Please not the past-tense of both. Your app was successful at both binding to an address and connecting to another host. Neither of these functions say ANYthing about monitoring the health of the connection.

How do people expect their computers to magically notice that a cable has been cut? Remember, people - it's all ones and zeroes. If some interrupt-line on your motherboard doesn't go from low to high or vice-versa, your CPU sees NOTHING. There is no direct connection between your computer and the far-away one; there is no current running out your ethernet port to every computer your computer might be in the process of talking to at any given moment. The ONLY WAY for your poor application to notice that it can't reach a given destination is for YOU to program in a "heartbeat" that tests occasionally.

This is not a result of "Sun just kidding developers". This is potzers who refuse to read, research, or understand the technology they're using trying to kid themselves into thinking they're developers.
</rant>

You're tripping over a basic reality of How TCP/IP (and hence the Entire Freakin Internet) Works. Go find Stevens' "UNIX Network Programming" (ISBN 0-13-490012-X.), and read it. Then read it again. Repeat until the giant glowing lightbulb appears over your head and an angelic chorus of deceased network engineers descends from the heavens repeating the seven OSI layers in Gregorian chant. Then you'll know you've Gotten It.

Grant
 
jschell
Posts:38,148
Registered: 11/3/97
Re: TCP client application does not detect network failure   
Aug 4, 2004 8:18 AM (reply 11 of 45)  (In reply to #8 )

 
Im also facing the same problem? I want to check the
availability of network using isConnected().. but it
gives a totally negative answer.

Im attaching my client and server program.
On client end : after making connection, the main
thread will sleep for 10 seconds, meanwhile I removed
the network cable, but the isConnected() and isBound()
methods returns true?

Is there any solution for this problem? Or sun just
kidding developers?

It has nothing to do with Sun, that is the way TCP works.

If you want to determine if a connection is valid then the only way to do so is to send something on it.
 
jschell
Posts:38,148
Registered: 11/3/97
Re: TCP client application does not detect network failure   
Aug 4, 2004 8:20 AM (reply 12 of 45)  (In reply to #10 )

 

You're tripping over a basic reality of How TCP/IP
(and hence the Entire Freakin Internet) Works. Go
find Stevens' "UNIX Network Programming" (ISBN
0-13-490012-X.), and read it. Then read it again.
Repeat until the giant glowing lightbulb appears over
your head and an angelic chorus of deceased network
engineers descends from the heavens repeating the
seven OSI layers in Gregorian chant. Then
you'll know you've Gotten It.

O'Reilly has a nice book out now too. It covers ICMP, UDP and TCP. (I can't recall the name of it now.)
 
Cipson_here
Posts:5
Registered: 3/8/04
Re: TCP client application does not detect network failure   
Aug 4, 2004 10:39 PM (reply 13 of 45)  (In reply to #12 )

 
the description seems 'present' tense for me....

boolean isBound()
Returns the 'binding state' of the socket.

boolean isConnected()
Returns the 'connection state' of the socket.


http://java.sun.com/j2se/1.4.2/docs/api/
 
ggainey
Posts:1,910
Registered: 23/08/97
Re: TCP client application does not detect network failure   
Aug 5, 2004 5:19 AM (reply 14 of 45)  (In reply to #13 )

 
the description seems 'present' tense for me....

http://java.sun.com/j2se/1.4.2/docs/api/

The quotes I gave come from exactly the same source. Here's the complete Javadoc for "isBound()", for example:

isBound
public boolean isBound()
Returns the binding state of the socket.

Returns: true if the socket successfuly bound to an address
Since: 1.4
See Also: bind(java.net.SocketAddress)

Usually, when I'm having a problem with a given piece of API, I try reading ALL of the documentation, rather than just the overview.

Grant
 
This topic has 45 replies on 4 pages.    1 | 2 | 3 | 4 | Next »
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 25
  • Guests : 132

About Sun forums
  • Oracle Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Oracle Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums