Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

HTTP head 2

Status
Not open for further replies.

Mausolo

Programmer
Jul 2, 2002
16
ES
I want to make a simple http server like this

import java.net.*;
import java.io.*;
public class MyHttpServer {

/** Creates a new instance of MyHttpServer */
public MyHttpServer() {
}
public void run()
{
try
{
int port = 10000;
ServerSocket srv = new ServerSocket(port);

// Wait for connection from client.
Socket socket = srv.accept();
System.out.println("Hello");
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write("Content-Type: text/html\r\n");
wr.write(&quot;<HTTP><BODY>OK</BODY></HTTP>&quot;);
wr.flush();
}
catch (IOException e) {
}


}

}


My i-explorer probe is:
htt://localhost:10000

The browser found nothing, and my class MyHttpServer write &quot;Hello&quot;.
Why?
Is this method of work correct? or is this a barbarism?

Thanks.
 
You need to close your Socket :

socket.close();

after you flush the stream at line wr.flush();
 
You need at least the following:

1. Wait for the web browser to send an empty line signaling it is done with its request.

2. Send HTTP/1.1 200 OK as first line of response.

3. You need an empty line between headers and html.

Code:
import java.net.*;
import java.io.*;

public class MyHttpServer {
    
  /** Creates a new instance of MyHttpServer */
  public MyHttpServer() {
  }
  public void run()
  {
    try
    {
      int port = 10000;
      ServerSocket srv = new ServerSocket(port);

      // Wait for connection from client.
      Socket socket = srv.accept();
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String line = in.readLine();
      while( (line != null) && (line.length() > 0) ) {
        System.out.println(&quot;client: &quot;+line);
        line = in.readLine();
      }

      BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
      wr.write(&quot;HTTP/1.1 200 OK\n&quot;);
      wr.write(&quot;Content-Type: text/html\n&quot;);
      wr.write(&quot;\n&quot;);
      wr.write(&quot;<HTTP><BODY>OK</BODY></HTTP>\n&quot;);
      wr.flush();
      wr.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws Exception {
    new MyHttpServer().run();
  }

}

Sean McEligot
 
If you don't close the socket, or explicaitly call socket.shutdownOutputStream() you won't see a response. Just closing the output stream is not enough to get a response on the browser.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top