Solved

HTTP listener

Posted on 2004-11-02
1,490 Views
Last Modified: 2012-05-05
Ola

I am looking for a minimal peice of code that listens on a HTTP port and accepts an icomming HTTP request.
This code should run on java 1.0 systems.

Or at least I want to know what classes i should use and where I can find information on them.
0
Question by:DaFou
    8 Comments
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    0
     
    LVL 14

    Assisted Solution

    by:sudhakar_koundinya
    //***************************************
    // HTTP Server
    // fpont June 2000
    // server implements HTTP GET method
    //***************************************


    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.lang.*;


    public class httpServer
    {
       
        public static void main(String args[]) {
          
          int port;
          ServerSocket server_socket;
          
          
          try {
              port = Integer.parseInt(args[0]);
          }
          catch (Exception e) {
              port = 1500;
          }
          

          try {
              
              server_socket = new ServerSocket(port);
              System.out.println("httpServer running on port " +
                             server_socket.getLocalPort());
              
              // server infinite loop
              while(true) {
                Socket socket = server_socket.accept();
                System.out.println("New connection accepted " +
                               socket.getInetAddress() +
                               ":" + socket.getPort());
                
                // Construct handler to process the HTTP request message.
                try {
                    httpRequestHandler request =
                      new httpRequestHandler(socket);
                    // Create a new thread to process the request.
                    Thread thread = new Thread(request);
                   
                    // Start the thread.
                    thread.start();
                }
                catch(Exception e) {
                    System.out.println(e);
                }
              }
          }
          
          catch (IOException e) {
              System.out.println(e);
          }
        }
    }


     
    class httpRequestHandler implements Runnable
    {
        final static String CRLF = "\r\n";
        Socket socket;
        InputStream input;
        OutputStream output;
        BufferedReader br;

        // Constructor
        public httpRequestHandler(Socket socket) throws Exception
        {
          this.socket = socket;
          this.input = socket.getInputStream();
          this.output = socket.getOutputStream();
          this.br =
              new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
       
        // Implement the run() method of the Runnable interface.
        public void run()
        {
          try {
              processRequest();
          }
          catch(Exception e) {
              System.out.println(e);
          }
        }
       
        private void processRequest() throws Exception
        {
          while(true) {
              
              String headerLine = br.readLine();
              System.out.println(headerLine);
              if(headerLine.equals(CRLF) || headerLine.equals("")) break;
              
              StringTokenizer s = new StringTokenizer(headerLine);
              String temp = s.nextToken();
              
              if(temp.equals("GET")) {

                String fileName = s.nextToken();
                fileName = "." + fileName ;
                
                // Open the requested file.
                FileInputStream fis = null ;
                boolean fileExists = true ;
                try
                    {
                      fis = new FileInputStream( fileName ) ;
                    }
                catch ( FileNotFoundException e )
                    {
                      fileExists = false ;
                    }
                
                // Construct the response message.
                String serverLine = "Server: fpont simple java httpServer";
                String statusLine = null;
                String contentTypeLine = null;
                String entityBody = null;
                String contentLengthLine = "error";
                if ( fileExists )
                    {
                      statusLine = "HTTP/1.0 200 OK" + CRLF ;
                      contentTypeLine = "Content-type: " +
                          contentType( fileName ) + CRLF ;
                      contentLengthLine = "Content-Length: "
                          + (new Integer(fis.available())).toString()
                          + CRLF;
                    }
                else
                    {
                      statusLine = "HTTP/1.0 404 Not Found" + CRLF ;
                      contentTypeLine = "text/html" ;
                      entityBody = "<HTML>" +
                          "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
                          "<BODY>404 Not Found"
                          +"<br>usage:http://yourHostName:port/"
                          +"fileName.html</BODY></HTML>" ;
                    }
                
                // Send the status line.
                output.write(statusLine.getBytes());
                
                // Send the server line.
                output.write(serverLine.getBytes());
                
                // Send the content type line.
                output.write(contentTypeLine.getBytes());
                
                // Send the Content-Length
                output.write(contentLengthLine.getBytes());
                
                // Send a blank line to indicate the end of the header lines.
                output.write(CRLF.getBytes());
                
                // Send the entity body.
                if (fileExists)
                    {
                      sendBytes(fis, output) ;
                      fis.close();
                    }
                else
                    {
                      output.write(entityBody.getBytes());
                    }
                            
              }
          }
          
          try {
              output.close();
              br.close();
              socket.close();
          }
          catch(Exception e) {}
        }
       
        private static void sendBytes(FileInputStream fis, OutputStream os)
          throws Exception
        {
          // Construct a 1K buffer to hold bytes on their way to the socket.
          byte[] buffer = new byte[1024] ;
          int bytes = 0 ;
          
          // Copy requested file into the socket's output stream.
          while ((bytes = fis.read(buffer)) != -1 )
              {
                os.write(buffer, 0, bytes);
              }
        }
       
        private static String contentType(String fileName)
        {
          if (fileName.endsWith(".htm") || fileName.endsWith(".html"))
              {
                return "text/html";
              }
          
          return "";
          
        }
       
    }
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    0
     
    LVL 2

    Author Comment

    by:DaFou
    And all of this certainly runs under java 1.0?
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    0
     
    LVL 13

    Assisted Solution

    by:petmagdy
    Hi DaFou,
    this is a sample in java unleached 1.2:

    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class HTTP09Server {
        // Version constants
        static final String NAME = "HTTP09Server";
        static final String VERSION = "1.0";
       // Variables for accessing configuration and logging objects
        ServerConfiguration config = new ServerConfiguration();
        Logger logger = new Logger();
        public static void main(String args[]){
            // Create a new server
            HTTP09Server server = new HTTP09Server();
            // Process command line arguments
            if(args.length>0) server.processCommandLine(args);
            // Run the server
            server.run();
        }
        public HTTP09Server() {
            super();
        }
        public void processCommandLine(String[] args) {
            for(int i=0;i<args.length;++i) {
                // Look for a configuration file
                if(args[i].equals("-CONFIG")) {
                    if(i+1<args.length)
                        config.processConfigurationFile(args[i+1]);
                   else
                   System.out.println("Configuration file argument is                 Amissing.");
                    break;
                }
            }
            String logFile = config.getLogFile();
            if(logFile!="") logger = new          ALogger(logFile,config.echoToConsole());
        }
        public void displayVersionInfo(){
            System.out.println("HTTP09Server version "+VERSION);
        }
        public void run() {
            displayVersionInfo();
            // Configure server
            config.display();
            try {
                // Create server socket, listen for and process incoming
                // connections
                ServerSocket server = new              AServerSocket(config.getServerPort());
                int localPort = server.getLocalPort();
                logger.datedLog(NAME+" is listening on port "+localPort+".");
                do {
                    Socket client = server.accept();
                    // Create a new thread to handle the connection
                    (new HTTP09ServerThread(client,config,logger)).start();
                } while(true);
            } catch(IOException ex) {
                 logger.datedLog("Unable to listen on "+
                 config.getServerPort()+".");
                System.exit(0);
            }
        }
    }
    class HTTP09ServerThread extends Thread {
        Socket client;
        ServerConfiguration config;
        Logger logger;
        public HTTP09ServerThread(Socket client,
                ServerConfiguration config, Logger logger) {
            this.client = client;
            this.config = config;
            this.logger = logger;
        }
        public void run() {
            try {
                // Send output to logging device
                describeConnection(client);
                // Set up I/O streams
                HTTPOutputStream outStream = new HTTPOutputStream(
                    new BufferedOutputStream(client.getOutputStream()));
                    HTTPInputStream inStream =
                 new HTTPInputStream(client.getInputStream());
                // Get and process client requests
                HTTPRequest request = inStream.getRequest();
                request.log(logger);
                if(request.isGetRequest())
                    processGetRequest(request,outStream);
                logger.datedLog("Request completed. Closing connection.");
            }catch(IOException ex) {
                logger.datedLog("IOException occured when processing              Arequest.");
            }
            try {
                client.close();
            }catch(IOException ex) {
                logger.datedLog("IOException occured when closing socket.");
            }
        }
        void describeConnection(Socket client) {
            String destName = client.getInetAddress().getHostName();
            String destAddr = client.getInetAddress().getHostAddress();
            int destPort = client.getPort();
            logger.datedLog("Accepted connection to "+destName+" ("
                +destAddr+")"+" on port "+destPort+".");
        }
        void processGetRequest(HTTPRequest request,HTTPOutputStream outStream)
                throws IOException {
            // What file is the client requesting?
            String fileName = request.getFileName(config);
            File file = new File(fileName);
            if(file.exists()) {
                // Figure out the file's full path name
                String fullPath = file.getCanonicalPath();
                // Is the file in the server root directory (or              Asubdirectories)?
                if(inServerRoot(fullPath)) {
                    int len = (int) file.length();
                    // Send the file to the requesting client
                    sendFile(outStream,file);
                }else logger.datedLog("File is not in server root.");
              }else logger.datedLog("File "+file.getCanonicalPath()+
             " does not exist.");
        }
        public boolean inServerRoot(String fileName) {
            String serverRoot = config.getServerRoot();
            int fileLength = fileName.length();
            int rootLength = serverRoot.length();
            if(fileLength<rootLength) return false;
            if(serverRoot.equals(fileName.substring(0,rootLength))) return          Atrue;
            return false;
        }
        void sendFile(HTTPOutputStream out,File file) {
            try {
                 DataInputStream in =
                 new DataInputStream(new FileInputStream(file));
                int len = (int) file.length();
                byte buffer[] = new byte[len];
                in.readFully(buffer);
                in.close();
                for(int i=0;i<len;++i) out.write(buffer[i]);
                out.flush();
                out.close();
                logger.datedLog("File sent: "+file.getCanonicalPath());
                logger.log("Number of bytes: "+len);
            }catch(Exception ex){
                logger.datedLog("Error retrieving "+file);
            }
        }
    }
    class HTTPInputStream extends FilterInputStream {
        public HTTPInputStream(InputStream in) {
            super(in);
        }
        public String readLine() throws IOException {
            StringBuffer result=new StringBuffer();
            boolean finished = false;
            boolean cr = false;
            do {
                int ch = -1;
                ch = read();
                if(ch==-1) return result.toString();
                result.append((char) ch);
                if(cr && ch==10){
                    result.setLength(result.length()-2);
                    return result.toString();
                }
                if(ch==13) cr = true;
                else cr=false;
            } while (!finished);
            return result.toString();
        }
        // Read and HTTP request from the input stream
        public HTTPRequest getRequest() throws IOException {
            HTTPRequest request = new HTTPRequest();
            String line;
            do {
                line = readLine();
                if(line.length()>0) request.addLine(line);
                else break;
            }while(true);
            return request;
        }
    }
    class HTTPOutputStream extends FilterOutputStream {
        public HTTPOutputStream(OutputStream out) {
            super(out);
        }
        public void println() throws IOException {
            write(13);
            write(10);
        }
        public void println(String s) throws IOException {
            for(int i=0;i<s.length();++i) write(s.charAt(i));
            println();
        }
    }
    // Class for encapsulating an HTTP request
    class HTTPRequest {
        Vector lines = new Vector();
       
        public HTTPRequest() {
        }
        public void addLine(String line) {
            lines.addElement(line);
        }
        boolean isGetRequest() {
            if(lines.size() > 0) {
                String firstLine = (String) lines.elementAt(0);
                if(firstLine.length() > 0)
                    if(firstLine.substring(0,3).equalsIgnoreCase("GET"))
                        return true;
            }
            return false;
        }
        String getFileName(ServerConfiguration config) {
            if(lines.size()>0) {
                String firstLine = (String) lines.elementAt(0);
                String fileName = firstLine.substring(firstLine.indexOf("              A")+1);
                int n = fileName.indexOf(" ");
                if(n!=-1) fileName = fileName.substring(0,n);
                try {
                    if(fileName.charAt(0) == `/')
                    fileName =  fileName.substring(1);
                } catch(StringIndexOutOfBoundsException ex) {}
                if(fileName.equals("")) fileName = config.getDefaultFile();
                if(fileName.charAt(fileName.length()-1)=='/')
                    fileName+=config.getDefaultFile();
                return config.getServerRoot()+fileName;
            }else return "";
        }
        void log(Logger logger) {
            logger.datedLog("Received the following request:");
            for(int i=0;i<lines.size();++i)
                logger.log((String) lines.elementAt(i));
        }
    }
    // Class for configuring the server
    class ServerConfiguration {
        static final char CONFIG_COMMENT_CHAR = `#';
        int serverPort = 80;
        String serverRoot = "";
        String defaultFile = "index.htm";
        String logFile = "";
        boolean echoLogToConsole = true;
        public ServerConfiguration() {
        }
        public char getCommentChar() {
            return CONFIG_COMMENT_CHAR;
        }
        public int getServerPort() {
            return serverPort;
        }
        public String getServerRoot() {
            return serverRoot;
        }
        public String getDefaultFile() {
            return defaultFile;
        }
        public String getLogFile() {
            return logFile;
        }
        public boolean echoToConsole() {
            return echoLogToConsole;
        }
        public void display() {
            System.out.println("  serverPort: "+serverPort);
            System.out.println("  serverRoot: "+serverRoot);
            System.out.println("  defaultFile: "+defaultFile);
            System.out.println("  logFile: "+logFile);
            System.out.println("  echoLogToConsole: "+echoLogToConsole);
        }
        public void processConfigurationFile(String fname) {
            try {
                File file = new File(fname);
                if(file.exists()) {
                     BufferedReader reader =
                     new BufferedReader(new FileReader(file));
                    String line;
                    while((line=reader.readLine())!=null)
                        processConfigurationLine(line);
                    reader.close();
                }
            }catch(Exception ex) {
                System.out.println("Unable to process configuration file.");
            }
        }
        public void processConfigurationLine(String line)
                throws NumberFormatException {
            line = removeLeadingWhiteSpace(line);
            if(line.length()==0) return;
            int n;
            int n1 = line.indexOf(` `);
            int n2 = line.indexOf(`\t');
            if(n1 == -1) n = n2;
            else if(n2 == -1) n = n1;
            else if(n1 < n2) n = n1;
            else n = n2;
            if(n==-1 || n==line.length()-1) return;
            String param = line.substring(0,n);
            String value = line.substring(n+1);
            if(param.equals("serverPort"))
                serverPort = (new Integer(value)).intValue();
            else if(param.equals("serverRoot")){
                serverRoot = value;
                if(!serverRoot.equals("")){
                    char ch = serverRoot.charAt(serverRoot.length()-1);
                    if(ch!='/' && ch!='\\') serverRoot+="/";
                }
            }else if(param.equals("defaultFile"))
                defaultFile = value;
            else if(param.equals("logFile"))
                logFile = value;
            else if(param.equals("echoLogToConsole"))
                echoLogToConsole = (new Boolean(value)).booleanValue();
        }
        String removeLeadingWhiteSpace(String line) {
            boolean finished = false;
            do {
                if(line.length()==0) return "";
                char ch = line.charAt(0);
                if(ch==CONFIG_COMMENT_CHAR) return "";
                if(ch!=' ` && ch!='\t') return line;
                line=line.substring(1);
            } while (!finished);
            return "";
        }
    }
    // Class for logging information about the server's operation
    class Logger {
        public String logFile;
        public boolean echoLogToConsole = true;
        public BufferedWriter writer = null;
        public Logger() {
        }
        public Logger(String fname, boolean echo) {
            logFile = fname;
            echoLogToConsole = echo;
            try {
                writer = new BufferedWriter(new FileWriter(fname,true));
            }catch(IOException ex){}
        }
        void logMsg(String msg) {
            if(writer!=null) {
                try {
                    writer.write(msg);
                    writer.newLine();
                    writer.flush();
                }catch(IOException ex){}
            }
            if(echoLogToConsole) System.out.println(msg);
        }
        public synchronized void log(String msg) {
            logMsg("  "+msg);
        }
        public synchronized void datedLog(String msg) {
            logMsg((new Date()).toString()+" "+msg);
        }
    }



    Cheers!
    0
     
    LVL 14

    Accepted Solution

    by:
    You can do onething

    compile files like this

    javac -target 1.0 *.java
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    thanks for accepting :)
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
    An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
    Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
    This video teaches viewers about errors in exception handling.

    884 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now