首页 > 代码库 > ServerSocket服务器

ServerSocket服务器

package cn.hackcoder.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {

	private static final String WEB_ROOT = System.getProperty("user.dir")
			+ File.separator + "webapp";
	private ServerSocket server;
	private static final String SHUT_DWON = "/shutdown";
	private static final int SIZE = 2048;

	HttpServer(int port, int backlog, String serverName) throws IOException {
		server = new ServerSocket(port, backlog,
				Inet4Address.getByName(serverName));
	}

	public void execute() throws IOException {
		
		BufferedInputStream bis = null;
		StringBuffer sb = null;
		byte[] bytes = new byte[SIZE];
		Socket client = null;
		while (true) {
			client = server.accept();
			OutputStream out = client.getOutputStream();
			System.out.println("============= 客户端连接上==========="
					+ client.getInetAddress());
			bis = new BufferedInputStream(client.getInputStream());
			sb = new StringBuffer();
			int ch = bis.read(bytes, 0, SIZE);
			for (int i = 0; i < ch; i++) {
				sb.append((char) bytes[i]);
			}
			System.out.println("==========请求内容===========\n" + sb);
			int index1 = sb.indexOf(" ");
			int index2 = sb.substring(index1 + 1).indexOf(" ");
			String name = "";
			if (index1 < index2)
				name = sb.substring(index1 + 1, index1 + index2 + 1);
			System.out.println("----------开始响应------------");
			File file = new File(WEB_ROOT, name);
			if (!file.exists() ||index1 > index2) {
				PrintStream ps = new PrintStream(out);
				ps.print("<h1>ERROR</h1>");
				bis.close();
				ps.close();
				continue;
			}
			InputStream in = new FileInputStream(file);
			int len = 0;
			len = in.read(bytes);
			while (len != -1) {
				out.write(bytes, 0, len);
				len = in.read(bytes);
			}
			System.out.println("------------响应结束------------");
			in.close();
			bis.close();
			out.close();
			System.out.println("服务器关闭");
		}
		
	}

	public static void main(String[] args) {
		try {
			new HttpServer(8888, 10, "127.1.1.111").execute();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

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


ServerSocket服务器