tags:

views:

62

answers:

1

According to Java documentation, the read() method returns:

  • -1 if there is no more data because the end the stream has been reached

I don't quite understand what they mean by "end of stream".

Currently I close/re-open the socket when this occurs (which I understood from much Googling to be an acceptable way to deal with this). Is -1 possibly "normal" behavior? Should I not react so dramatically? Perhaps it would be better to only get upset on an IOException?

Socket creation:

clientSocket = new Socket(InetAddress.getByName(remoteHost), remotePort, InetAddress.getByName(sourceIpAddress), 0);

Some background information:

  • i am using the 'localAddr' attribute when creating the socket (project requirement)
  • i am running under Windows XP SP2
  • i have no idea how the remote server is handling sockets (or even what language, not that that should matter)
  • this occurs very rarely (perhaps once a day)
  • only happens with one specific remote client running Linux
  • the trouble-some client and myself are both behind numerous firewalls
  • this never occurs with clients running various flavors of XP (perhaps it's time to setup a VMware image running Linux!)
+1  A: 

The other end of the socket has closed the stream, so there is no more data to read - you've reached the end. I'd diagnose further with a network monitor such as Wireshark as to why the socket gets closed.

nos
But is -1 a guarantee that the socket is really, truly closed? I was able to still send data to this socket without causing an exception, though I can't say if the other end actually received it.Wireshark is a great tip. Unfortunately I started it AFTER this happened and it hasn't happened since.
glenneroo
The Socket abstraction supports the notion that the input and output sides of the communication can be closed independently. So, if the other end has closed its output but not input, you can continue writing socket output after you've got an end of stream on your socket input.
Stephen C