java笔记 - 如何用socket做一个简单的http server

功能, 接受input, 将httpheader 返回

import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.net.*;

public class TestSocket_Server {
	class MySocketHandler implements Runnable {

		@Override
		public void run() {
			try {
				println("Incoming found@" + s0.getPort());
				HandleIncomingSocket(s0);
			} catch (Exception e) {
				println("Exception: " + e.getMessage());
			} finally {
				try {	
					println("Closing Socket.");
					s0.close();
				} catch (Exception e2){}
				println("Socket closed!");
			}
		}
		public Socket s0;
	}
	public static void main(String[] args) throws Exception {
		new TestSocket_Server().Run();
	}//main()
	public void Run() throws Exception{
		ServerSocket ss = new ServerSocket(80);
		ExecutorService service= Executors.newCachedThreadPool();
		for (int i=0;i<10;i++) {
			printf("%d/10: Waiting incoming connection...\n", i+1);
			Socket s0=ss.accept();
			MySocketHandler receiver = new MySocketHandler();
			receiver.s0 = s0;
			service.execute(receiver);
		}
		println("shutdown now");
		service.shutdown();
		service.awaitTermination(10, TimeUnit.SECONDS);
		
		println("Quit now");
	}
	public static void HandleIncomingSocket(Socket s) throws Exception {
		TestSocket_AddressesAndInterfaces util=new TestSocket_AddressesAndInterfaces();
		util.printInetAddress(s.getInetAddress());
		InputStream in=s.getInputStream();
		byte[] buffer = new byte[1024*1024*10];
		File fTemp = File.createTempFile("temp", ".txt");
		printf("Temp file %s created\n", fTemp.getAbsolutePath());
		printf("IsClosed = %s, IsConnected=%s, IsInputShutdown=%s, IsOutputShutdown=%s\n"
				, s.isClosed(), s.isConnected(), s.isInputShutdown(), s.isOutputShutdown());
		printf("available=%d\n", in.available());
		int nReads = 0;
		if(in.available() >0)
			nReads = in.read(buffer);
		while(nReads>0) {
			FileOutputStream fs = new FileOutputStream(fTemp,true);
			fs.write(buffer, 0, nReads);
			fs.flush();
			fs.close();
			printf("IsClosed = %s, IsConnected=%s, IsInputShutdown=%s, IsOutputShutdown=%s\n"
					, s.isClosed(), s.isConnected(), s.isInputShutdown(), s.isOutputShutdown());
			nReads = 0;
			if (in.available()>0)
				nReads = in.read(buffer);
		} 
		printf("%d bytes read from client\n", fTemp.length());
		StringBuilder bld = new StringBuilder();
		bld.append(String.format("Received %d bytes<br/>\n", fTemp.length()));
		bld.append("Here's the text I got, pls. verify<br/><br/>\n");
		if (fTemp.length()>0) {			
			Scanner sc=new Scanner(fTemp);
			while(sc.hasNextLine()) {
				String line = sc.nextLine();
				line +="<br/>\r\n";
				bld.append(line);
				printf(line);
			}
			sc.close();
		}
		
		OutputStream out = s.getOutputStream();
		byte[] content=bld.toString().getBytes();
		int nLen=content.length;
		bld = new StringBuilder();
		bld.append("HTTP/1.0 200 OK\r\n");
		bld.append("Last-Modified: Sat, 10 Mar 2012 14:42:12 GMT\r\n");
		bld.append("Accept-Ranges: bytes\r\n");
		bld.append("Content-Type: text/html\r\n");
		bld.append("Date: Sat, 10 Mar 2012 14:46:19 GMT\r\n");
		bld.append("Server: TestServer\r\n");
		bld.append("Expires: Sat, 10 Mar 1900 14:47:19 GMT\r\n");
		bld.append(String.format("Content-Length: %d\r\n", nLen));
		bld.append("Connection: close\r\n");
		bld.append("\r\n");
		out.write(bld.toString().getBytes());
		out.write(content);
		out.flush();
		out.close();
	}
	private static void printf(String format, Object... args) {
		System.out.print(Thread.currentThread().getId());
		System.out.print('\t');
		if (args == null || args.length == 0) {
			System.out.print(format);
		} else {
			System.out.printf(format, args);
		}
	}
	private static void println(String msg) {
		System.out.print(Thread.currentThread().getId());
		System.out.print('\t');
		System.out.println(msg);
	}
	
}

posted on 2012-03-11 13:22  learner  阅读(1973)  评论(0)    收藏  举报

导航