Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Simple HTTP-Server

  1. #1
    Junior Member
    Join Date
    Jul 2012
    Location
    Germany
    Posts
    3
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Simple HTTP-Server

    Hey guys,

    after the OneShotHttpServer was running, I wanted to try out the extended version. Somehow theres a problem again. This time when I want to compile the .java in the command shell it says:

    Note: SimpleHTTpd2.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    Ok. So I found out how to compile with Xlint and it says:

    SimpleHttpd2.java:109: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type Hashtable
    myHeaders.put(key, value);

    where K,V are type-variables:
    K extends Object declared in class Hashtable
    V extends Object declared in class Hashtable
    1 warning
    So.. theres something "wrong" with this method here in line 109?

    protected void setHeader(String key, String value){
           myHeaders.put(key, value);
    }

    Here's the code for the whole programme:

    package httpServer;
     
    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class SimpleHttpd2 extends Thread {
     
    protected Socket s = null;
    protected static File docRoot;
    protected static String canonicalDocRoot;
     
    public final static int HTTP_PORT = 8080;
    public final static String CRLF = "\r\n";
    public final static String PROTOCOL = "HTTP/1.0 ";
     
    public final static String SC_OK = "200 OK";
    public final static String SC_BAD_REQUEST = "400 Bad Request";
    public final static String SC_FORBIDDEN = "403 Forbidden";
    public final static String SC_NOT_FOUND = "404 Not Found";
     
    protected static Properties typeMap = new Properties();
    protected String statusCode = SC_OK;
    protected Hashtable myHeaders = new Hashtable();
     
    	public static void main(String[] args) {
    		try {
    			typeMap.load(new FileInputStream("index.html"));
    			docRoot = new File (".");
    			canonicalDocRoot = docRoot.getCanonicalPath();
    			ServerSocket listen = new ServerSocket(HTTP_PORT);
    			while(true){
    				SimpleHttpd2 aRequest = new SimpleHttpd2(listen.accept());
    			}
    		}
    			catch(IOException e) {
    				System.err.println("Fehler: " + e.toString());
    			}
    		}
     
    	public SimpleHttpd2(Socket s) {
    		this.s = s;
    		start();
    	}
     
    	public void run() {
    		try {
    			setHeader("Server", "SimpleHttpd2");
    			BufferedReader is = new BufferedReader(new InputStreamReader(s.getInputStream()));
    			DataOutputStream os = new DataOutputStream(s.getOutputStream());
    			String request = is.readLine();
    			System.out.println("Request: " + request);
    			StringTokenizer st = new StringTokenizer(request);
    			if ((st.countTokens()==3) && st.nextToken().equals("GET")) {
    				String filename = docRoot.getPath() + st.nextToken();
    				if (filename.endsWith("/") || filename.equals(""))
    					filename += "index.html";
    				File file = new File(filename);
    				if (file.getCanonicalPath().startsWith(canonicalDocRoot))
    					sendDocument(os, file);
    				else
    					sendError(SC_FORBIDDEN, os);
    			}
    			else {
    				sendError(SC_BAD_REQUEST, os);
    			}
    			is.close();
    			os.close();
    			s.close();
    		}
    		catch ( IOException ioe) {
    			System.err.println("Fehler: " + ioe.toString());
    		}
    	}
     
    	protected void sendDocument(DataOutputStream os, File file) throws IOException {
    		try {
    			BufferedInputStream in = new BufferedInputStream (new FileInputStream(file));
    			sendStatusLine(os);
    			setHeader("Content-Length", (new Long(file.length())).toString());
    			setHeader("Content-Type", guessType(file.getPath()));
    			sendHeader(os);
    			os.writeBytes(CRLF);
    			byte[] buf = new byte[1024];
    			int len;
    			while ((len = in.read(buf, 0, 1024)) != -1) {
    				os.write(buf, 0, len);
    			}
    			in.close();
    		}
    		catch (FileNotFoundException fnfe) {
    			sendError(SC_NOT_FOUND, os);
    		}
    	}
     
    	protected void setStatusCode(String statusCode) {
    		this.statusCode = statusCode;
    	}
     
    	protected String getStatusCode() {
    		return statusCode;
    	}
     
    	protected void sendStatusLine(DataOutputStream out) throws IOException {
    		out.writeBytes(PROTOCOL + getStatusCode() + CRLF);
    	}
     
    	protected void setHeader(String key, String value) {
    		myHeaders.put(key, value);
    	}
     
    	protected void sendHeader(DataOutputStream out) throws IOException {
    		String line;
    		String key;
    		Enumeration e = myHeaders.keys();
    		while (e.hasMoreElements()) {
    			key = (String)e.nextElement();
    			out.writeBytes(key + ": " + myHeaders.get(key) + CRLF);
    		}
    	}
     
    	protected void sendError(String statusCode, DataOutputStream out) throws IOException {
    		setStatusCode(statusCode);
    		sendStatusLine(out);
    		out.writeBytes(
    				CRLF
    				+ "<html>"
    				+ "<head><title>" + getStatusCode() + "</title></head>"
    				+ "<body><hl>" + getStatusCode() + "</hl></body>"
    				+ "</html>"
    		);
    		System.err.println(getStatusCode());
    	}
     
    	public String guessType(String filename) {
    		String type = null;
    		int i = filename.lastIndexOf(".");
    		if (i > 0)
    			type = typeMap.getProperty(filename.substring(i));
    		if (type == null)
    			type = "unknown/unknown";
    		return type;
    	}
    }

    Is there someone out there who knows how to fix that problem?

    Zaphod_B.. do you have an idea?

    Edit: ok I put the index.html in the project folder this time the programme works with my IDE. However the header data etc is not given out as it should. Only "Request: GET / HTTP/1.1" Maybe theres something missing in the programme.

    Edit: I changed the out.writeBytes() stuff with System.out.println() and now he gives out a lot more. Dont know yet if everything works properly as it should, but at least it works better now. Someone knows why the out.writeBytes() dont work?

    Now the output when I enter http://localhost:8080/ in my browser is:

    Request: GET / HTTP/1.1
    HTTP/1.0 200 OK

    Server: SimpleHttpd2

    Content-Type: unknown/unknown

    Content-Length: 44

    Request: GET /favicon.ico HTTP/1.1
    HTTP/1.0 404 Not Found

    404 Not Found
    Request: GET /favicon.ico HTTP/1.1
    HTTP/1.0 404 Not Found

    404 Not Found
    And someone knows why there is 2x in the output:

    Request: GET /favicon.ico HTTP/1.1
    HTTP/1.0 404 Not Found

    404 Not Found
    ?
    Last edited by v1per1987; July 27th, 2012 at 06:50 AM.


  2. #2
    Member
    Join Date
    Jul 2012
    Posts
    69
    My Mood
    Relaxed
    Thanks
    1
    Thanked 6 Times in 6 Posts

    Default Re: Simple HTTP-Server

    I dont know how to fix your server, but a small hint:
    Try to use the
     
    tags. It makes it so much easier to read for other people .

  3. The Following User Says Thank You to elamre For This Useful Post:

    v1per1987 (July 27th, 2012)

  4. #3
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Simple HTTP-Server

    Quote Originally Posted by v1per1987 View Post
    ...compile the .java in the command ...
    protected void setHeader(String key, String value){
           myHeaders.put(key, value);
    }
    There is nothing wrong with that line. The message was about the declaration of myHeaders.

    Change the declaration of myHeaders (somewhere around line 22)

    from
    protected Hashtable myHeaders = new Hashtable();

    to

    protected Hashtable<String,String> myHeaders = new Hashtable<String,String>();
    Quote Originally Posted by v1per1987
    Here's the code for the whole programme:

    .
    .
    .
    			typeMap.load(new FileInputStream("index.html")); //<--- This doesn't make sense.  typeMap is used to identify the mime type of a file
    .
    .
    .
    Change that line to
                typeMap.load(new FileInputStream("mime.types"));

    Create a file named "mime.types" in the same directory. Paste the following into mime.types:
    <xmp>
      .ra=audio/x-realaudio
      .wav=audio/x-wav
      .gif=image/gif
      .jpeg=image/jpeg
      .jpg=image/jpeg
      .png=image/png
      .tiff=image/tiff
      .html=text/html
      .htm=text/html
      .txt=text/plain
     </xmp>
    Quote Originally Posted by v1per1987
    I put the index.html in the project folder this time the programme works with my IDE
    Well, I can't see how it sends valid stuff to your browser when you try to use the server I mean, it can print a line in the console window where you launched the server, but as a server, it is kaput until you get a typeMap loaded.

    Quote Originally Posted by v1per1987
    Edit: I changed the out.writeBytes() stuff with System.out.println() and now he gives out a lot more.
    Well, System.out.println() writes stuff to the terminal window, and the writeBytes stuff is sending the stuff out the socket to service http requests, so getting things to print on the console can be a useful debugging tool, but it doesn't make it work as a server. That stuff has got to go out the socket! Go back to your original code. Change the typeMap declaration and do the mime.types thing I suggested. Try localhost:8080 from your browser again.

    Do you have an Ethernet packet sniffer like Wireshark? (Used to be called Ethereal.) If you don't, then I respectfully suggest that if you are going to be doing anything serious in the area of network programming that you install it.

    Bottom line: If the mime.types file is properly implemented, when you enter the "localhost:8080" in your browser URL window, you should see the processed html in the browser window.

    If index.html contains <html>Hi, Zaphod!</html>, you should see Hi, Zaphod! in the browser window. (Unlike the previous example, which showed the entire text contents of index.html, including the <> html tags.)

    Then--- it's time to have a little fun with more interesting index.html stuff before going to the next step.


    Cheers!


    Z
    Last edited by Zaphod_b; July 27th, 2012 at 05:24 PM.

Similar Threads

  1. One-Shot-HTTP-Server
    By v1per1987 in forum Java Networking
    Replies: 3
    Last Post: July 24th, 2012, 04:35 PM
  2. Can't form a simple POST or GET http request. No data returns.
    By goodguy in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 29th, 2011, 05:04 AM
  3. simple ftp server and ftp client
    By simontkk2005 in forum Java Networking
    Replies: 4
    Last Post: January 26th, 2011, 10:29 AM
  4. Replies: 6
    Last Post: September 19th, 2010, 08:33 PM
  5. Replies: 1
    Last Post: March 31st, 2010, 09:42 PM