//file: TinyHttpd.java
import java.net.*;
import java.io.*;
import java.util.*;
public class TinyHttpd {
public static void main( String argv[] ) throws IOException {
ServerSocket ss =
new ServerSocket( Integer.parseInt(argv[0]) );
while ( true )
new TinyHttpdConnection( ss.accept() ).start( );
}
} // end of class TinyHttpd
class TinyHttpdConnection extends Thread {
Socket client;
TinyHttpdConnection ( Socket client ) throws SocketException {
this.client = client;
setPriority( NORM_PRIORITY - 1 );
}
public void run( ) {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream( ), "8859_1" ));
OutputStream out = client.getOutputStream( );
PrintWriter pout = new PrintWriter(
new OutputStreamWriter(out, "8859_1"), true );
String request = in.readLine( );
System.out.println( "Request: "+request );
StringTokenizer st = new StringTokenizer( request );
if ( (st.countTokens( ) >= 2)
&& st.nextToken( ).equals("GET") ) {
if ( (request = st.nextToken( )).startsWith("/") )
request = request.substring( 1 );
if ( request.endsWith("/") || request.equals("") )
request = request + "index.html";
try {
FileInputStream fis = new FileInputStream ( request );
byte [] data = new byte [ fis.available( ) ];
fis.read( data );
out.write( data );
out.flush( );
} catch ( FileNotFoundException e ) {
pout.println( "404 Object Not Found" ); }
} else
pout.println( "400 Bad Request" );
client.close( );
} catch ( IOException e ) {
System.out.println( "I/O error " + e ); }
}
}
|