Re: How to know that the server side has close the connection when
using java socket?
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.
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.
2. If the socket is an SSLSocket, available() will always return 0. Some
InputStreams do that as well.
It never will be: the ServerConnection class implementing the receive()
method is only created by a companion ListenerConnection class that
constructs it from a vanilla Socket.
3. You're allocating a new buffer every time around the loop. This is
churning memory. Move that buffer declaration outside both loops.
That may be an issue in C. Java has good gc handling for transient
objects, so the scope extension that would require is not necessary.
4. If lth < 0 you should break the loop *and* close the socket.
That's one way. I prefer to use explicit open() and close() operations
for classes that handle files and sockets. This makes correctness by
inspection easier for the calling code as well as ensuring that
constructors don't throw exceptions.
5. You're assuming that every chunk of bytes read, of whatever length,
can be turned into a String. This assumption isn't valid.
It is in the limited application scope for which this method was
implemented. See above.
--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |