(without any security)
import java.net.*;
import java.io.*;
import java.util.Vector;
import java.util.Date;
import java.util.StringTokenizer;
public class MyServer extends Thread
{
private ServerSocket listener = null;
private int port = MySocket.DEFAULT_PORT;
/** Start the server.*/
public static void main(String args[])
{
new MyServer().start();
}
/** Run the server.*/
public void run()
{
try
{
listener = new ServerSocket(port);
}
catch(IOException e)
{
System.err.println(e); System.exit(1);
}
System.out.println("Listening on "+listener);
while (true)
{
try
{
Socket connection = listener.accept();
MyConnectionHandler handler =
new MyConnectionHandler(connection);
handler.start();
}
catch(IOException e)
{
System.err.println("Exception:" + e);
}
}
}
}
/** Handles a request from a client.*/
class MyConnectionHandler extends MySocket
{
MyConnectionHandler(Socket socket)
{
super(socket);
}
/** Load a file from the filesystem.*/
public String load_from_file(String filename)
{
try
{
return load(
new BufferedReader(
new FileReader(
new File(filename))));
}
catch(FileNotFoundException file_not_found_exception)
{
System.err.println(filename+" read error:"
+file_not_found_exception+"!");
//file_not_found_exception.printStackTrace();
}
return null;
}
/** Handle the request. */
public void run()
{
try
{
String request= receiveLine();
System.out.println("Request for " + request +".");
StringTokenizer tokenizer = new StringTokenizer(request);
if (tokenizer.nextToken().equalsIgnoreCase("GET")
&&tokenizer.hasMoreElements())
{
String name = System.getProperty("user.dir")+
tokenizer.nextToken();
String data = load_from_file(name);
if (data!=null)
{
send ("HTTP/1.0 200 OK\015\012");
send ("Connection: Keep-Alive\015\012");
send ("Date: "+ new Date()+"\015\012");
send ("Server: JCT's Server 1.0\015\012");
send ("Content-Encoding: ASCII\015\012");
send ("Content-Length: " + data.length()+"\015\012");
if (name.endsWith(".class"))
send ("Content-Type: application/class\015\012");
else if (name.endsWith(".gif"))
send ("Content-Type: image/gif\015\012");
else
send ("Content-Type: text/html\015\012");
send ("\015\012");
send (data);
send ("\015\012");
}
else
send ("HTTP/1.0 404 Not Found\015\012");
}
else
send("No Service");
socket.close();
}
catch (IOException e )
{
e.printStackTrace();
}
System.out.println("Disconnecting: "
+ socket.getInetAddress() +":"
+ socket.getPort());
stop();
}
}
|