Create A web server with ServerSocket in Java

Description

The following code shows how to create A web server with ServerSocket.

Example


   // w  ww .j  ava  2  s.c o m
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
  public static void main(String args[]) throws Exception {
    ServerSocket ss = new ServerSocket(80);
    while (true) {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String info = null;
      while ((info = in.readLine()) != null) {
        System.out.println("now got " + info);
        if (info.equals(""))
          break;
      }
      out.println("HTTP/1.0 200 OK");
      out.println("MIME_version:1.0");
      out.println("Content_Type:text/html");
      String c = "<html> <head></head><body> <h1> hi</h1></Body></html>";
      out.println("Content_Length:" + c.length());
      out.println("");
      out.println(c);
      out.close();
      s.close();
      in.close();
    }
  }
}




















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode