Re: How to know that the server side has close the connection when using java socket?
Martin Gregorie wrote:
On Thu, 25 Sep 2008 01:31:05 +0000, EJP wrote:
Martin Gregorie wrote:
n = 1;
while (n > 0)
{
byte [] received = new byte[MAXBUFF]; lth =
in.read(received);
if (lth >= 0)
buff.append(new String(received, 0, lth));
n = in.available();
}
Well there are *lots* of problems with this code.
Not really: it works well within its intended application area. It is
part of a suite of classes (ClientConnection, ListenerConnection,
ServerConnection) that use standard TCP/IP connections to transfer ASCII
request/response message pairs between clients and a server.
1. Don't use available() == 0 to indicate completion of a request, or to
indicate EOS either; it doesn't mean that.
It does what I intended: it will allow messages that have been sent as
single units to be reassembled if the TCP/IP stack should fragment them.
Actually it won't. It might some of the time, in fact it might all of the time -
up until the first time it doesn't. There is no such guarantee from
available(), all it tells you is how much data is waiting in the input buffer.
The TCP/IP stack will present whatever data is available as it becomes
available. If only some of the packets have arrived, provided they are complete
in sequence up to that point, those packets are likely to be available() and
you will only get a partial message.
TCP/IP does not know anything about "message" or "record" structures within the
data stream because TCP/IP has no concept of structure. It is a simple
sequential byte stream. Attempting to use available() to add structure to the
stream is ultimately doomed to failure. In practice it might work forever, but
it is a fatally flawed algorithm.
A more robust approach would be to precede every message with a fixed
length byte count and then read until the right number of bytes have been
received but so far that has not been necessary.
It is the only valid way to read a specific number of bytes from a TCP/IP
stream. You've been lucky so far, and your luck will almost certainly run out
eventually. Algorithms that rely on luck should be reserved for gambling
establishments ;-)
--
Nigel Wade