JAvaネットワークプログラミング-socket単純シミュレーションhttpサーバ


TcpServer:
package com.fsun.research.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
	@SuppressWarnings("unused")
	public static void main(String[] args) {
		ServerSocket tcpServer=null;
		try {
			tcpServer=new ServerSocket(4523);
		} catch (IOException e) {
			e.printStackTrace();
			if(tcpServer!=null){
				try {
					tcpServer.close();
				} catch (IOException e1) {
					tcpServer=null;
				}
			}
			return ;
		}
		Socket socket=null;
		while(true){
			try {
				socket=tcpServer.accept();
				Thread thread=new Thread(new HttpClientThread(socket));
				thread.start();
			} catch (IOException e) {
				if(socket!=null){
					try {
						socket.close();
					} catch (IOException e1) {
						socket=null;
					}
				}
			}
		}
	}
}

HttpClientThread:
package com.fsun.research.httpserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;

public class HttpClientThread implements Runnable{
	private Socket socket;
	private InputStream is;
	private OutputStream os;
	private PrintWriter printStream;
	private BufferedReader br;
	private StringBuilder requestStr;
	public HttpClientThread(Socket socket) {
		super();
		this.socket = socket;
		this.requestStr=new StringBuilder();
		try {
			this.is=socket.getInputStream();
			this.os=socket.getOutputStream();
			this.printStream=new PrintWriter(new OutputStreamWriter(this.os));
			this.br=new BufferedReader(new InputStreamReader(this.is,Charset.defaultCharset()));
		} catch (IOException e) {
		}
		
	}
	@Override
	public void run() {
		String str=null;
		try {
			while(StringUtils.isNotEmpty(str=this.br.readLine())){
				requestStr.append(str);
			}
			System.out.println(" http :");
			System.out.println(this.requestStr.toString());
			sendResponse();
			close();
		} catch (IOException e) {
		}
	}
	private void close() {
		try {
			this.is.close();
			this.os.close();
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	private void sendResponse() {
		this.printStream.println("HTTP/1.1 200 OK");
		this.printStream.println("Date:Mon,6Oct2003 13:23:42 GMT");
		this.printStream.println("Content-Type: text/html;charset=UTF-8");
		this.printStream.println(" http ");
		this.printStream.flush();
		this.printStream.close();
	}
}