Java Reference
In-Depth Information
Example 9-10. An HTTP server that serves a single file
import java.io.* ;
import java.net.* ;
import java.nio.charset.Charset ;
import java.nio.file.* ;
import java.util.concurrent.* ;
import java.util.logging.* ;
public class SingleFileHTTPServer {
private static final Logger logger = Logger . getLogger ( "SingleFileHTTPServer" );
private final byte [] content ;
private final byte [] header ;
private final int port ;
private final String encoding ;
public SingleFileHTTPServer ( String data , String encoding ,
String mimeType , int port ) throws UnsupportedEncodingException {
this ( data . getBytes ( encoding ), encoding , mimeType , port );
}
public SingleFileHTTPServer (
byte [] data , String encoding , String mimeType , int port ) {
this . content = data ;
this . port = port ;
this . encoding = encoding ;
String header = "HTTP/1.0 200 OK\r\n"
+ "Server: OneFile 2.0\r\n"
+ "Content-length: " + this . content . length + "\r\n"
+ "Content-type: " + mimeType + "; charset=" + encoding + "\r\n\r\n" ;
this . header = header . getBytes ( Charset . forName ( "US-ASCII" ));
}
public void start () {
ExecutorService pool = Executors . newFixedThreadPool ( 100 );
try ( ServerSocket server = new ServerSocket ( this . port )) {
logger . info ( "Accepting connections on port " + server . getLocalPort ());
logger . info ( "Data to be sent:" );
logger . info ( new String ( this . content , encoding ));
while ( true ) {
try {
Socket connection = server . accept ();
pool . submit ( new HTTPHandler ( connection ));
} catch ( IOException ex ) {
logger . log ( Level . WARNING , "Exception accepting connection" , ex );
} catch ( RuntimeException ex ) {
logger . log ( Level . SEVERE , "Unexpected error" , ex );
}
}
} catch ( IOException ex ) {
Search WWH ::




Custom Search