import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.Socket;
public class ConnectionThread extends Thread
{
Socket client;
int counter;
String defaultPath;
//constructor
public ConnectionThread(Socket sock, int count, String defPath) {
client = sock;
counter = count;
defaultPath = defPath;
}
//check the request method is "GET" or not
private boolean getRequest(String requestLine) {
if (requestLine.length() > 0) {
if (requestLine.substring(0, 3).equalsIgnoreCase("GET")) {
return true;
}
}
return false;
}
//get file name from client request
private String getFileName(String requestLine) {
String fileName = requestLine.substring(requestLine.indexOf(' ')+1);
fileName = fileName.substring(0, fileName.indexOf(' '));
try {
if (fileName.charAt(0) == '/') {
fileName = fileName.substring(1);
}
} catch(StringIndexOutOfBoundsException e) {
System.out.println("Exception" + e.toString());
}
//default web page
if (fileName.equals("")) {
fileName = "index.html";
}
return fileName;
}
//send file to client
private void sendFile(PrintStream outStream, File file) {
try {
//read file in stream
DataInputStream inStream = new DataInputStream(new FileInputStream(file));
int length = (int)file.length();
byte buf[] = new byte[length];
inStream.readFully(buf);
outStream.write(buf, 0, length);
outStream.close();
inStream.close();
} catch(Exception e) {
System.out.println("Error retrieving file!!");
System.exit(1);
}
}
//analysis the client request ,and response
public void run() {
try {
String destip = client.getInetAddress().toString();
int destport = client.getPort();
System.out.println("Connection" + counter + ": connected to " + destip + " on port " + destport + ".");
PrintStream outStream = new PrintStream(client.getOutputStream());
DataInputStream inStream = new DataInputStream(client.getInputStream());
String inline = inStream.readLine();
System.out.println("Received : " + inline);
if (getRequest(inline)) {
String fileName = getFileName(inline);
File file = new File(defaultPath + fileName);
if (file.exists()) {
System.out.println(fileName + " requested.");
outStream.println("HTTP/1.1 200 OK");
outStream.println("MIME-version:1.0");
outStream.println("Content-Type:text/html");
int length = (int)file.length();
outStream.println("Content-Length:"+length);
outStream.println("");
sendFile(outStream, file);
outStream.flush();
}
}
else {
String errorReq = "<html><head><title>Not Found</title><body><h1>Error 404 not found</h1></body></html>";
outStream.println("HTTP/1.1 404 no found");
outStream.println("Content-Type:text/html");
outStream.println("Content-Length:" + (errorReq.length()+2));
outStream.println("");
outStream.println(errorReq);
outStream.flush();
}
client.close();
} catch(Exception e) {
}
}
}