`
mycream
  • 浏览: 54220 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

ServerSocket

    博客分类:
  • JAVA
阅读更多

找到本好书,《How Tomecat Work》。嘻嘻,按里面的章节学习中。

今天仿写了一个非常简单的 HttpServer,可是在第二次访问时就出错了。郁闷啊,还不知道原因,先记录一下,下次再研究出错的原因。

package server;

import java.io.*;
import java.net.*;

/**
 * HttpServer to handler HTTP request.
 *
 * @author Cream
 * @since 2011-06-06
 */
public class HttpServer {
	public static final String WEB_ROOT = System.getProperty("user.dir")
		+ File.separator;

	private final String SHUTDOWN_COMMAND = "/SHUTDOWN";

	private int port = 8080;
	private boolean shutdown = false;

	public static void main(String[] args) {
		HttpServer server = new HttpServer();
		server.await();
	}

	public void await() {
		ServerSocket server = null;
		try {
			server = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
		// Loop waiting for a request
		while (!shutdown) {
			Socket socket = null;
			InputStream input = null;
			OutputStream output = null;
			try {
				socket = server.accept();
				input = socket.getInputStream();
				output = socket.getOutputStream();

				Request request = new Request(input);
				request.parse();

				Response response = new Response(output);
				response.setRequest(request);
				response.sendStaticResource();

				// Close the socket
				socket.close();

				// Check if the previous URI is a shutdown command
				shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
	}
}
 
package server;

import java.io.*;
import java.net.*;

public class Request {

	private final InputStream input;
	private String uri;

	public Request(InputStream input) {
		this.input = input;
	}

	public String getUri() {
		return this.uri;
	}

	public void parse() throws IOException {
		StringBuffer request = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(input);
		BufferedReader reader = new BufferedReader(isr);

		try {
			// Now we only read the first line to get URI.
			String header = null;
			if (reader.ready()) { // 这里出错了,貌似不是总是 ready 状态的。
				header = reader.readLine();
				this.uri = parseUri(header);
			}

			// Output the other HTTP header information
			System.out.println(header);
			while (reader.ready()) {
				System.out.println(reader.readLine());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			if (input != null) {
				input.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String parseUri(String header) {
		int index1, index2;
		index1 = header.indexOf(' ');
		if (index1 != -1) {
			index2 = header.indexOf(' ', index1 + 1);
			if (index2 > index1) {
				return header.substring(index1 + 1, index2);
			}
		}
		return null;
	}
}
 
package server;

import java.io.*;
import java.net.*;

public class Response {
	private int BUFFER_SIZE = 8192;
	private final OutputStream output;
	private Request request;

	public Response(OutputStream output) {
		this.output = output;
	}

	public void setRequest(Request request) {
		this.request = request;
	}

	public void sendStaticResource() throws IOException {
		byte[] bytes = new byte[BUFFER_SIZE];
		String uri = request.getUri();
		System.out.println("HttpServer.WEB_ROOT:" + HttpServer.WEB_ROOT);
		File file = new File(HttpServer.WEB_ROOT, uri);
		FileInputStream fis = null;

		try {
			if (file.exists()) {
				// Output file
				fis = new FileInputStream(file);
				int ch = fis.read(bytes, 0, BUFFER_SIZE);
				while (ch != -1) {
					output.write(bytes, 0, ch);
					ch = fis.read(bytes, 0, BUFFER_SIZE);
				}
			} else {
				// File not found
				String errorMessage = "HTTP/1.1 404 File Not Found\r\n"
					+ "Content-Type: text/html\r\n"
					+ "Content-Length: 23\r\n"
					+ "\r\n"
					+ "<h1>File Not Found</h1>";
				output.write(errorMessage.getBytes());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
 
1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics