import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
public class BasicServer
{
public static void main
(String[] args
)
{
final int SERVER_PORT = 1986;
String servPath =
"src/pociu/cis201/server/wwwroot/";
try
{
}
{
System.
err.
println("Could not listen on port: " + SERVER_PORT
);
}
while (true)
{
try
{
clientSocket = serverSocket.accept();
}
{
System.
err.
println("Accept failed.");
}
try
{
out =
new PrintWriter(clientSocket.
getOutputStream(),
true);
out.flush();
while (!(s = in.readLine()).isEmpty())
{
if(s.length() > 0)
{
// Unfortunately Java won't do Switch on strings...
if(tokens.nextToken().equals("GET"))
{
String fileRequested = tokens.
nextToken().
replace("/",
"");
//Remove the query string before attempting to retrieve the file from the file system
fileRequested = RemoveQString(fileRequested);
if(fileRequested.equals("")) // If the root is requested
{
fileRequested = "index.html"; // Show the index.html page
}
File reqFile =
new File(servPath + fileRequested
);
System.
out.
println("File " + fileRequested +
" was requested.");
if(reqFile.exists())
{
try
{
while ((line = bfFile.readLine()) != null)
{
out.write(line);
}
out.flush();
bfFile.close();
System.
out.
println("The file was served.");
}
{
out.write("The file you have requested (" + fileRequested + ") could not be served: " + e.getMessage());
out.flush();
System.
out.
println("An IO exception occured.");
}
}
else
{
out.write("The file you have requested (" + fileRequested + ") was not found.");
out.flush();
System.
out.
println("File not found.");
}
}
}
}
out.close();
in.close();
clientSocket.close();
}
{
e.printStackTrace();
}
}
}
{
int qPos = str.indexOf("?");
if(qPos >= 0)
{
str = str.substring(0, qPos);
}
return str;
}
}