Web Science/Part1: Foundations of the web/Hypertext Transfer Protocol/A simple web server
Aspetto
A simple web server
nessun obbiettivo di apprendimento definito
Tu puoi definire gli obiettivi di apprendimento qui.
In generale puoi usare il bottone di modifica nell'angolo in alto a destra di una sezione per modificarne il contenuto.
In generale puoi usare il bottone di modifica nell'angolo in alto a destra di una sezione per modificarne il contenuto.
SimpleWebServer.java
[modifica]/*
* 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
[modifica]/*
* 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
[modifica]/*
* 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
[modifica]- Java API for a server socket
- Some directory in the file system
- being able to respond to any get request