Java Server: Socket sending HTML code to browser -
i trying write simple java program using serversockets send html code browser. here code:
serversocket serversocket = null; try { serversocket = new serversocket(55555); } catch (ioexception e) { system.err.println("could not listen on port: 55555."); system.exit(1); } socket clientsocket = null; try { clientsocket = serversocket.accept(); if(clientsocket != null) system.out.println("connected"); } catch (ioexception e) { system.err.println("accept failed."); system.exit(1); } printwriter out = new printwriter(clientsocket.getoutputstream()); out.println("http/1.1 200 ok"); out.println("content-type: text/html"); out.println("\r\n"); out.println("<p> hello world </p>"); out.flush(); out.close(); clientsocket.close(); serversocket.close();
i go localhost:55555 in browser , nothing displays. know connection working because program outputs "connected" checked in if statement. have tried outputting data inputstream , works. text trying output in browser not displaying @ all, program finishes running , "problem loading page - connection has been reset" in browser, no text.
i have searched internet , seems else coding way having text display fine, having other problems. how can fix this?
i tested code in chrome, firefox, ie, , opera , works.
however, suggest use multi-threading , spawn new thread handle each new request.
you can create class implements runnable , takes clientsocket within constructor. make custom webserver capable of accepting more 1 request concurrently.
you need while loop if want handle more 1 total requests.
a read demonstrating above: http://www.prasannatech.net/2008/10/simple-http-server-java.html
enjoy!
Comments
Post a Comment