Web Science/Part1: Foundations of the web/Web Architecture/Hypertext Transfer Protocol/A Simple Web Server

From Wikiversity
Jump to: navigation, search

New-here.png NewDiscussionButton.png Feed-icon.svg



Quick Navigation: Video - Script - further Reading - Quiz - Discussion


Video of the lesson: A Simple Web Server

Add-to-watchlist-HOCH.png

Quick Navigation: Video - Script - further Reading - Quiz - Discussion

Script for: A Simple Web Server

SimpleWebServer.java

/*
 * Copyright (C) 2013 Rene Pickhardt
 * Contact via http://www.rene-pickhardt.de or rene@rene-pickhardt.de
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package demo;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
 
/**
 * The purpose is to demonstrate how to build a simple Web Server on top
 * of TCP / IP. Therefore, we just make a very simple HTTP GET request. 
 */
public class SimpleWebServer {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			ServerSocket httpServerSocket = new ServerSocket(8080);
 
			Socket incommingHttpConnection = null;
 
			while ((incommingHttpConnection = httpServerSocket.accept()) != null){
				BufferedReader br = new BufferedReader(new InputStreamReader(incommingHttpConnection.getInputStream()));
 
				String line = br.readLine();
				// GET /test/simiple.html HTTP/1.0
 
				String path = processFirstLine(line, incommingHttpConnection);
 
				if (path != null){
					SimpleWebRequest request = new SimpleWebRequest(path);
					while ((line = br.readLine())!= null){
						if (line.equals("")){
							makeResponse(request, incommingHttpConnection);
							break;
						}
						// Example
						// Host:studywebscience.org\r\n
						request.addHeaderField(line);
					}
				}
				br.close();
				incommingHttpConnection.close();
				incommingHttpConnection = null;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
	}
 
	private static void makeResponse(SimpleWebRequest request,
			Socket incommingHttpConnection) {
		// /test/simple.html
		String body = fetchAsciiFile(request.getPath());
		if (body == null){
			makeErrorResponse("404 Not Found", incommingHttpConnection);
		} else {
			SimpleWebResponse resp = new SimpleWebResponse(incommingHttpConnection);
			resp.setStatusCode("200 Ok");
			resp.setBody(body);
			resp.writeToSocket();
		}
 
	}
 
	private static String fetchAsciiFile(String path) {
		try {
			StringBuilder body = new StringBuilder(100000);
			BufferedReader br = new BufferedReader(new FileReader(new File(System.getProperty("user.dir") + "/webdirectory" + path)));
			String tmp = null; 
			while ((tmp = br.readLine())!= null){
				body.append(tmp + "\n");
			}
			br.close();
			return body.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
 
	private static String processFirstLine(String line, Socket incommingHttpConnection) {
		if (line == null)
			return null;
		String path = null;
		if (!line.startsWith("GET") && line.split("\\s").length !=3 ){
			makeErrorResponse("400 Bad Request", incommingHttpConnection);
		} else {
			String [] values = line.split("\\s");
			path = values[1];
			if (!(values[2].equals("HTTP/1.0") || values[2].equals("HTTP/1.1"))){
				makeErrorResponse("400 Bad Request", incommingHttpConnection);
			}
		}
		return path;
	}
 
	private static void makeErrorResponse(String errorCode,
			Socket incommingHttpConnection) {
		SimpleWebResponse resp = new SimpleWebResponse(incommingHttpConnection);
		resp.setStatusCode(errorCode);
		resp.writeToSocket();
	}
 
}

SimpleWebRequest.java

/*
 * Copyright (C) 2013 Rene Pickhardt
 * Contact via http://www.rene-pickhardt.de or rene@rene-pickhardt.de
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package demo;
 
import java.util.HashMap;
 
/**
 * The purpose is to demonstrate how to build a simple Web Server on top
 * of TCP / IP. Therefore, we just make a very simple HTTP GET request. 
 */
public class SimpleWebRequest {
	private HashMap<String, String> headerFields = null;
 
	public SimpleWebRequest(String path) {
		headerFields = new HashMap<String, String>();
		headerFields.put("path", path);
		// TODO Auto-generated constructor stub
	}
 
	public String getPath(){
		return headerFields.get("path");
	}
 
	public void addHeaderField(String line) {
		int index = line.indexOf(":");
		if (index < 0) return;
		String key = line.substring(0, index).trim();
		String value = line.substring(index+1, line.length());
		headerFields.put(key, value);
	}
 
}

SimpleWebResponse.java

/*
 * Copyright (C) 2013 Rene Pickhardt
 * Contact via http://www.rene-pickhardt.de or rene@rene-pickhardt.de
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package demo;
 
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
 
/**
 * The purpose is to demonstrate how to build a simple Web Server on top
 * of TCP / IP. Therefore, we just make a very simple HTTP GET request. 
 */
public class SimpleWebResponse {
	private Socket connection = null;
	private String statusCode = null;
	private String body = "";
 
 
	public SimpleWebResponse(Socket incommingHttpConnection) {
		connection = incommingHttpConnection;
	}
 
	public void setStatusCode(String statusCode) {
		this.statusCode = statusCode;
 
	}
 
	public void setBody(String body){
		this.body = body;
	}
 
	public void writeToSocket() {
		try {
			OutputStream os = connection.getOutputStream();
 
			String response = "HTTP/1.0 " + statusCode + "\r\n";
 
			response += "Date:" + new Date(System.currentTimeMillis()) + "\r\n";
 
			response += "\r\n";
 
			response += body;
 
			os.write(response.getBytes());
			os.flush();
			os.close();
 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

script

  • Java API for a serversocket
  • Some directory in the file system
  • being able to respond to any get request

Quick Navigation: Video - Script - further Reading - Quiz - Discussion

Further information, readings and exercises about A Simple Web Server



Quick Navigation: Video - Script - further Reading - Quiz - Discussion

Discuss A Simple Web Server with others

QuestionButton.png DiscussionButton.png

Join the discussion: Ask and questions and provide answers

  • If you click the ask a question button you're question will appear at the bottom of this list.
  • If you click the give an answer you will be able to provide an answer to the questions that have been asked so far.

Notes on the video/code

This is just a pure personal opinion: I prefer well-documented code to a (long) video. Besides that, I want to remark that the FSF recommends using the word "Copyright", noting the year and copying the official licence text (or at least link it) when releasing under GPL. --Onse (discusscontribs) 09:17, 12 November 2013 (UTC)

feel free to add comments to the source code. it is under a free license and you have access to it (: In general: I also prefer well documented code but I made the experience in the case of learning that live programming is kind of the best method in order to walk people through code at the right speed. It makes them see the trains of thought... --Renepick (discusscontribs) 09:23, 12 November 2013 (UTC)

QuestionButton.png DiscussionButton.png


Previous-mooc-lesson.png Parent-mooc-lesson.png Next-mooc-lesson.png

navigational context


Video
and script
Associated Lesson
Making HTTP requests
A Simple Web Client
A Simple Web Server
The HTTP Header
Content negotiation
Summary, Further readings, Homework

The following video of the flipped classroom associated with this topic are available:

You can find more information on wiki commons and also directly download this file