SUSE Linux iTOps Tube

Wednesday, May 9, 2012

[Java] Running A Basic Web Server

Hi There;

There is a java class that implements basic web server.It gets the port number from console. This code is very basic, it returns what the client sends.Here are the codes:


package p106;



public class HttpMirror {

        public static void main(String[] args) {



                        //Get the port.

                        int port = Integer.parseInt(args[0]);


                        //Create a socket for listening that port.

                        ServerSocket ss = new ServerSocket(port);





                                /* Wait for connection from the client. Routine will be blocked when

                                * it returns the socket that connected to the client. 

                                * */

                                Socket client = ss.accept();


                                //Set the input and output in order to talk with the client.

                                BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream()));

                                PrintWriter out = new PrintWriter(client.getOutputStream());


                                out.print("HTTP/1.0 200 en");

                                out.print("Content-Type text/plain");


                                /* At that point, read HTTP request and send it back to the client.


                                * */


                                String line;

                                while( (line = in.readLine()) != null)


                                        if(line.length() == 0)


                                        out.print(line );








                        } // Tekrar döngüye gir ve bir sonraki bağlantıyı bekle.

                }catch(Exception e)






My OS is ubuntu 11.10. My browser is Mozilla Firefox. My IDE is Eclipse. First of all, I give "4444" as a port number, by the way this code will accept 4444 as a port number. And press "Run" button in eclipse. When the code runs, I start firefox and I type "localhost:4444" and "", but there is no result, there is a blank page in browser.

What is the problem, how can I solve it?How can that class work?

Thanks in advance.