HTTP Web Server

Hi. I am trijing to develop a simple HTTP web server using JAVA.

My question e browser send post or get messages.
Bu my server dont stop to reading messages.

String line = "";
                        int ch;
                        while ((ch = br.read()) != -1) {
                              line += (char)ch;
                              System.out.print((char) ch);
                        }

Process dont go out while.

How can I stop reading messages.
AbsenteAsked:
Who is Participating?
 
CEHJCommented:
>>
I will solve like this.
is it true  ?
>>

That's more like it, yes.
0
 
CEHJCommented:
The first thing you need to do if you want to write your own web server (not a trivial task) is what an http request is and how it's formed
0
 
for_yanCommented:
How are you posting and reading the messages - are you using sockets or some other mechanism.

You pribably want to post much more of your code.
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
AbsenteAuthor Commented:
public class WebServer {

// Directory of HTML pages and other files
	protected String docroot;
	// Port number of web server
	protected int port;
	// Socket for the web server
	protected ServerSocket ss;

	// Handler for a HTTP request
	class Handler extends Thread {
		protected Socket socket;
		protected PrintWriter pw;
		protected BufferedOutputStream bos;
		protected BufferedReader br;
		protected File docroot;

		public Handler(Socket _socket, String _docroot) throws Exception {
			socket = _socket;
			// Get the absolute directory of the filepath
			docroot = new File(_docroot).getCanonicalFile();
		}

		public void run() {
			try {
				// Prepare our readers and writers
				br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				bos = new BufferedOutputStream(socket.getOutputStream());
				pw = new PrintWriter(new OutputStreamWriter(bos));

				// Read HTTP request from user (hopefully GET /file...... )
				System.out.println("New Request: ");
				String line = "";
				String ch;
				int count = 0;
                while (!"".equals(ch = br.readLine())) {
					line += ch;
					System.out.println("=====> "+ch);
				}
				
				// Shutdown any further input
				socket.shutdownInput();

				if (line == null) {
					socket.close();
					return;
				}
				if (line.toUpperCase().startsWith("GET")) {
					// Eliminate any trailing ? data, such as for a CGI GET
					// request
					StringTokenizer tokens = new StringTokenizer(line, " ?");
					tokens.nextToken();
					String req = tokens.nextToken();

					// If a path character / or \ is not present, add it to the
					// document root
					// and then add the file request, to form a full filename
					String name;
					if (req.startsWith("/") || req.startsWith("\\"))
						name = this.docroot + req;
					else
						name = this.docroot + File.separator + req;

					// Get absolute file path
					File file = new File(name).getCanonicalFile();

					// Check to see if request doesn't start with our document
					// root ....
					if (!file.getAbsolutePath().startsWith(this.docroot.getAbsolutePath())) {
						pw.println("HTTP/1.0 403 Forbidden");
						pw.println();
					}
					// ... if it's missing .....
					else if (!file.exists()) {
						pw.println("HTTP/1.0 404 File Not Found");
						pw.println();
					}
					// ... if it can't be read for security reasons ....
					else if (!file.canRead()) {
						pw.println("HTTP/1.0 403 Forbidden");
						pw.println();
					}
					// ... if its actually a directory, and not a file ....
					else if (file.isDirectory()) {
						sendDir(bos, pw, file, req);
					}
					// ... or if it's really a file
					else {
						sendFile(bos, pw, file.getAbsolutePath());
					}
				}
				// If not a GET request, the server will not support it
				else {
					pw.println("HTTP/1.0 501 Not Implemented");
					pw.println();
				}

				pw.flush();
				bos.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				socket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		protected void sendFile(BufferedOutputStream bos, PrintWriter pw, String filename) throws Exception {
			try {
				java.io.BufferedInputStream bis = new java.io.BufferedInputStream(new FileInputStream(filename));
				byte[] data = new byte[10 * 1024];
				int read = bis.read(data);

				pw.println("HTTP/1.0 200 Okay");
				pw.println();
				pw.flush();
				bos.flush();

				while (read != -1) {
					bos.write(data, 0, read);
					read = bis.read(data);
				}
				bos.flush();
			} catch (Exception e) {
				pw.flush();
				bos.flush();
			}
		}

		protected void sendDir(BufferedOutputStream bos, PrintWriter pw,
				File dir, String req) throws Exception {
			try {
				pw.println("HTTP/1.0 200 Okay");
				pw.println();
				pw.flush();

				pw.print("<html><head><title>Directory of ");
				pw.print(req);
				pw.print("</title></head><body><h1>Directory of ");
				pw.print(req);
				pw.println("</h1><table border=\"0\">");

				File[] contents = dir.listFiles();

				for (int i = 0; i < contents.length; i++) {
					pw.print("<tr>");
					pw.print("<td><a href=\"");
					pw.print(req);
					pw.print(contents[i].getName());
					if (contents[i].isDirectory())
						pw.print("/");
					pw.print("\">");
					if (contents[i].isDirectory())
						pw.print("Dir -> ");
					pw.print(contents[i].getName());
					pw.print("</a></td>");
					pw.println("</tr>");
				}
				pw.println("</table></body></html>");
				pw.flush();
			} catch (Exception e) {
				pw.flush();
				bos.flush();
			}
		}
	}

	// Check that a filepath has been specified and a port number
	protected void parseParams(String[] args) throws Exception {
		this.docroot = "";
		this.port = 8080;
	}

	public WebServer(String[] args) throws Exception {
		System.out.println("Checking for paramters");

		// Check for command line parameters
		parseParams(args);

		System.out.print("Starting web server...... ");

		// Create a new server socket
		this.ss = new ServerSocket(this.port);

		System.out.println("OK");

		for (;;) {
			// Accept a new socket connection from our server socket
			Socket accept = ss.accept();

			// Start a new handler instance to process the request
			new Handler(accept, docroot).start();
		}
	}

	// Start an instance of the web server running
	public static void main(String[] args) throws Exception {
		WebServer webServerDemo = new WebServer(args);
	}
}

It is the full code.

Open in new window

0
 
AbsenteAuthor Commented:
I will solve like this.
is it true  ?

            int count = 0;
                while (!"".equals(ch = br.readLine())) {
                              line += ch;
                              System.out.println("=====> "+ch);
                        }
is Each post ort get request have a empty line at the end.
0
 
for_yanCommented:


>Process dont go out while.

That is actually expected behavior - this reading is blocking process - if you do not get the next line
from the srrver it will be sitting there waiting
0
 
AbsenteAuthor Commented:
My other Qestions.

1.
I send a request to open webpage from my browser to my web server.
is this request always vie get request ? is it possible to open web page  with post request witout get reguest.

2. How can I get data from my form suubmision via post method ?
0
 
CEHJCommented:
It will sometimes be a post request - it would depend on what the resource is and what is going to it
Rather than engaging in an ongoing conversation here about how these things work, i suggest you read the specs or at least digested versions of them. You're not going to do this efficiently otherwise
0
 
AbsenteAuthor Commented:
ok.
I sent post reguest with a button. How can I cath the values from form ?
0
 
for_yanCommented:
0
 
AbsenteAuthor Commented:
My form dont send form values.


=====> POST /page.html HTTP/1.1
=====> Host: localhost:8080
=====> Connection: keep-alive
=====> Content-Length: 59
=====> Cache-Control: max-age=0
=====> Origin: http://localhost:8080
=====> User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2
=====> Content-Type: application/x-www-form-urlencoded
=====> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
=====> Referer: http://localhost:8080/mypage4.html
=====> Accept-Encoding: gzip,deflate,sdch
=====> Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
=====> Accept-Charset: ISO-8859-9,utf-8;q=0.7,*;q=0.3


;Where is the form values ?.
it sents content size but. not send contens.
0
 
CEHJCommented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.