java - Try/catch block with a while statement, used to handle socket data, does not continue. No obvious errors (I think) -
this main class - main.java. used control requester added completeness.
import java.io.ioexception; import htmlrequester.requester; public class main { public static void main(string[] args) { requester rq = new requester("www.google.co.za", 80); try { rq.htmlrequest(); } catch (ioexception e) { e.printstacktrace(); system.err.println("connection failed."); system.exit(-1); } } }
this requester.java, edited shortness.
package htmlrequester; import java.net.*; import java.io.*; public class requester{ socket httpsocket = null; printwriter out = null; bufferedreader in = null; string server; int port; public void setattributes(string server, int port){ this.server = server; this.port = port; } public string htmlrequest(string server, int port) throws ioexception{ try { httpsocket = new socket(inetaddress.getbyname(server), port); out = new printwriter(httpsocket.getoutputstream(), true); in = new bufferedreader(new inputstreamreader( httpsocket.getinputstream())); } catch (unknownhostexception e) { system.err.println("don't know host: " + server); system.exit(-1); } catch (ioexception e) { system.err.println("couldn't i/o " + "the connection to: " + server + "on port " + port); system.exit(-1); } finally{ system.out.println("successful connection."); } out.println(compilerequesttext()); out.println(""); string t; string ret = ""; system.out.println("wait..."); try { while((t = in.readline()) != null) { ret.concat(t); system.out.println(t); } system.out.println("done"); } catch(socketexception e) { system.err.println("socket exception :("); } system.out.println("succesful data transfer."); out.close(); in.close(); httpsocket.close(); return ret; } private string compilerequesttext(){ string ret = "get / http/1.1"; return ret; } }
what happens second try-catch block in request.java, block contains:
while((t = in.readline()) != null)
will execute, , response server displayed. however, after response displayed, loop stop executing, code not move ahead block. program not seem continue after while loop. have idea why?
i.e., system.out.println("done"); never reached, no exceptions or compiler errors being thrown.
your request incomplete: should add connection: close
header, , host
header. see example http://www.jmarshall.com/easy/http/#http1.1clients
what happening server leaving connection open can send more requests through it, , loop stays trying read results. header disabled behavior asking server close connection.
closing output stream server after sending request works, too.
Comments
Post a Comment