I'm creating a Java socket in Javascript, sending an HTTP request and receiving a response correctly but I seem to be unable to detect an EOF or the server closing the socket at the end. What am I doing wrong? The problem is we never exit the outermost while loop - the server stops transmitting and (presumably) closes its end of the connection, yet receiver.read() never returns -1 and all the socket methods return state consistent with the socket still being connected.
var s = new java.net.Socket("www.google.com",80);
var sender = new java.io.PrintStream(s.getOutputStream());
var receiver = s.getInputStream();
sender.print("GET / HTTP/1.0\r\n\r\n");
sender.flush();
s.shutdownOutput();
var response = '';
var eof = 0;
while( !eof && s.isConnected() && s.isBound() && !s.isClosed() && !s.isInputShutdown() )
{
if( receiver.available() )
{
while( receiver.available() )
{
var i = receiver.read();
if( i == -1 ) { eof = 1; }
else { response += String.fromCharCode(i); }
}
// at this point response does contain the expected HTTP response
}
}
// in case remote end closed the socket before we got a chance to read all the bytes from it
// ...but this is never reached!
while( receiver.available() )
{
response += String.fromCharCode(receiver.read());
}
alert( response );