Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.cooksys.httpserver; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLServerSocketFactory; import org.apache.http.HttpConnectionFactory; import org.apache.http.HttpServerConnection; import org.apache.http.impl.DefaultBHttpServerConnection; import org.apache.http.impl.DefaultBHttpServerConnectionFactory; import org.apache.http.protocol.HttpService; /** * * @author Tim Davidson HTTP simple server - this code was taken directly from * Apache's HTTP Components documentation located at: * http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java * * Main server thread - listens for connections on server socket, and then * spawns a worker thread for each incoming connection */ class RequestListenerThread extends Thread { private final HttpConnectionFactory<DefaultBHttpServerConnection> connFactory; private final ServerSocket serversocket; private final HttpService httpService; private boolean serverRunning; public void stopServer() { try { //close the connection in order to interrupt the accept() blocking call this.serversocket.close(); } catch (IOException ex) { Logger.getLogger(RequestListenerThread.class.getName()).log(Level.SEVERE, null, ex); } } public RequestListenerThread(final int port, final HttpService httpService) throws IOException { this.connFactory = DefaultBHttpServerConnectionFactory.INSTANCE; this.serversocket = new ServerSocket(port); this.httpService = httpService; } @Override public void run() { System.out.println("Listening on port " + this.serversocket); while (!Thread.interrupted()) { try { // Listen for connections Socket socket = this.serversocket.accept(); System.out.println("Incoming connection from " + socket.getInetAddress()); //setup the http connection HttpServerConnection conn = this.connFactory.createConnection(socket); // Start worker thread Thread t = new WorkerThread(this.httpService, conn); t.setDaemon(true); t.start(); } catch (InterruptedIOException ex) { break; } catch (IOException e) { System.err.println("Connection interrupted. " + e.getMessage()); break; } } //clean up socket connection before exiting thread System.out.println("Server thread exiting"); } }