import java.io.IOException; /** * Entry is HTTP Server entry, each socket create a thread * @author hui.wang * */ public class Entry { public static void main(String[] args){ try{ Server server = new Server(8080); server.run(); } catch(IOException e) { System.err.println("Error binding the specified port."); } } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; /** * Service support echo input to output * @author hui.wang * */ public class Service extends Thread { private Socket _socket; public Service(Socket socket) { _socket = socket; } public void run(){ try{ //Wrapper the InputStream to BufferedReader BufferedReader input = new BufferedReader(new InputStreamReader(_socket.getInputStream())); //Wrapper the OutputStream to BuffedWriter BufferedWriter output = new BufferedWriter(new OutputStreamWriter(_socket.getOutputStream())); String line = input.readLine(); while( line != null ) { if(line.equals("quit")) return; output.write(line + "\r\n"); output.flush(); line = input.readLine(); } input.close(); output.close(); } catch(IOException e){ //Abandon the current connection } finally{ try{ //Close the connection. _socket.close(); } catch(IOException e){ //Eat the IOException } } } }
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * One server instance, create service to execute operation. * @author hui.wang * */ public class Server implements Runnable { private ServerSocket _server; public Server(int port) throws IOException { // This statement will throw out IOException // if the specified port is not available. _server = new ServerSocket(port); } public void run() { try { for (;;) { // Accept an incoming connection. Socket client = _server.accept(); // Create a Service Thread to serve the client. Service service = new Service(client); service.start(); } } catch (IOException e) { // Eat the IOException } } }