HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Programming an HTTP Web Server with Java"
Vol. 2, Issue 5, p. 22

	

Listing 1: Serve.java.

import java.net.*;
import java.io.*;
import java.awt.*;

public class Serve extends Frame implements Runnable{
     Serve(){
        setTitle("Server Program");
        Panel p = new Panel();
        portInput = new TextField(String.valueOf(port),4);
        startButton = new Button("Start Server");
        stopButton = new Button("Stop Server");
        p.add(new Label("Port:"));
        p.add(portInput);
        p.add(startButton);
        p.add(stopButton);
        add("North",p);

        a = new TextArea(50,30);
        add("Center",a);
        resize(300,300);
        show();

    }
    public void run(){
        port=Integer.parseInt(portInput.getText());
        display("Server Started on Port:"+port+"\n");
        try{
            ss = new ServerSocket(port);
            while(true){
                display("listening again ** port: "+port+"\n");
                Socket s = ss.accept();
                new Thread(new FileRequest(s,this)).start();
                display("got a file request \n");
            }

        } catch(Exception e){ display("$$$$ exception "+e+"\n");}
    }
    public boolean handleEvent(Event evt){
        if(evt.id==Event.WINDOW_DESTROY){
             System.exit(0);
             return true;
        }
        if((evt.id==Event.ACTION_EVENT)&&(evt.target instanceof Button)){
                if(runner != null){
                    runner.suspend();
                    display("Server Stopped By User\n");
                }
            }
            if(evt.target == startButton){
               if(runner == null){
                runner = new Thread(this);
                runner.start();
                portInput.setEditable(false);
               }else{runner.resume();
            }
        }
        return super.handleEvent(evt);


    }

    public synchronized void display(String text){
        a.appendText(text);
    }
    public static void main(String[] args){
        new Serve();
    }
    private ServerSocket ss;
    private TextArea a;
    private int port = 80 ;
    private TextField portInput;
    private Button startButton, stopButton;
    private Thread runner=null;
}

Listing 2: FileRequest.java

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

class FileRequest implements Runnable{


    FileRequest(Socket s, Serve app){
        this.app=app;
        client = s;
    }
    public void run(){

        if(requestRead()){
            if(fileOpened()){
                constructHeader();
                if(fileSent()){
                    app.display("*File: "+fileName+" File Transfer Complete*Bytes Sent:"+bytesSent+"\n");
                }
            }
        }
          try{
            dis.close();
            client.close();
        }catch(Exception e){app.display("Error closing Socket\n"+e);}

    }


    private boolean fileSent()
    {
        try{
            DataOutputStream clientStream = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
            clientStream.writeBytes(header);
            app.display("******** File Request *********\n"+
                        "******* "+ fileName +"*********\n"+header);
            int i;
            bytesSent = 0;
            while((i=requestedFile.read()) != -1){
                clientStream.writeByte(i);
                bytesSent++;
            }
            clientStream.flush();
            clientStream.close();
		 }catch(IOException e){return false;}
		 return true;

    }
    private boolean fileOpened()
    {
        try{
                requestedFile = new DataInputStream(new BufferedInputStream (new FileInputStream("wwwroot/"+fileName)));
                fileLength = requestedFile.available();
                app.display(fileName+" is "+fileLength+" bytes long.\n");
            }catch(FileNotFoundException e){
                if(fileName.equals("filenfound.html")){return false;}
                fileName="filenfound.html";
                if(!fileOpened()){return false;}
            }catch(Exception e){return false;}


			return true;

    }
    private boolean requestRead()
    {
         try{
            //Open inputStream and read(parse) the request
            dis = new DataInputStream(client.getInputStream());
            String line;
            while((line=dis.readLine())!=null){

                StringTokenizer tokenizer = new StringTokenizer(line," ");
                if(!tokenizer.hasMoreTokens()){ break;}

                        if(tokenizer.nextToken().equals("GET")){

                            fileName = tokenizer.nextToken();
                            if(fileName.equals("/")){
                                fileName = "index.html";
                            }else{
                                fileName = fileName.substring(1);
                            }

                        }

            }

         }catch(Exception e){

            return false;
         }
           app.display("finished file request");

         return true;
    }


    private void constructHeader(){
        String contentType;
        if((fileName.toLowerCase().endsWith(".jpg"))||(fileName.toLowerCase().endsWith(".jpeg"))||(fileName.toLowerCase().endsWith(".jpe")))
            {contentType = "image/jpg";}
        else if((fileName.toLowerCase().endsWith(".gif")))
            {contentType = "image/gif";}
        else if((fileName.toLowerCase().endsWith(".htm"))||(fileName.toLowerCase().endsWith(".html")))
            {contentType = "text/html";}
        else if((fileName.toLowerCase().endsWith(".qt"))||(fileName.toLowerCase().endsWith(".mov")))
            {contentType = "video/quicktime";}
        else if((fileName.toLowerCase().endsWith(".class")))
            {contentType = "application/octet-stream";}
        else if((fileName.toLowerCase().endsWith(".mpg"))||(fileName.toLowerCase().endsWith(".mpeg"))||(fileName.toLowerCase().endsWith(".mpe")))
            {contentType = "video/mpeg";}
        else if((fileName.toLowerCase().endsWith(".au"))||(fileName.toLowerCase().endsWith(".snd")))
            {contentType = "audio/basic";}
        else if((fileName.toLowerCase().endsWith(".wav")))
            {contentType = "audio/x-wave";}
        else {contentType = "text/plain";} //default

        header = "HTTP/1.0 200 OK\n"+
                 "Allow: GET\n"+
                 "MIME-Version: 1.0\n"+
                 "Server : HMJ Basic HTTP Server\n"+
                 "Content-Type: "+contentType + "\n"+
                 "Content-Length: "+ fileLength +
                 "\n\n";
    }

    private Serve app;
    private Socket client;
    private String fileName,header;
    private DataInputStream requestedFile, dis;
	private int fileLength, bytesSent;

}


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.