用jdk5提供的Executor 接口,Executors类可以创建单线程,多线程,线程池等。具体请看AIP.中是静态方法获取。
package com.ccl.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Hashtable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
public class HttpPoolService {
private final int HTTP_PORT;
private ServerSocket listen = null;
private Hashtable<String, String> knownRequests = new Hashtable<String, String>();
public HttpPoolService(int port) {
this.HTTP_PORT = port;
if (HTTP_PORT <= 0) {
System.out.println("port Illegal:" + HTTP_PORT);
return;
}
try {
this.listen = new ServerSocket(HTTP_PORT);
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void start() throws SocketException {
Executor service = Executors.newCachedThreadPool();// thread pool
Logger log = Logger.getLogger("practical");
while (true) {
Socket s = null;
try {
s = listen.accept();// Block waiting for connection
} catch (IOException e) {
e.printStackTrace();
}
HandleRequest handle = new HandleRequest(s, knownRequests, log);
service.execute(handle);
// System.out.println(s.getKeepAlive());
}
}
/**
* @param urlPath
* @param data
*/
public void registerRequest(String urlPath, String data) {
knownRequests.put(urlPath.trim(), data);
}
/**
* @param urlPath
*/
public void removeRequest(String urlPath) {
knownRequests.remove(urlPath);
}
/**
* @author ChengChenglun
* @param args
* @throws UnsupportedEncodingException
* @throws SocketException
*/
public static void main(String[] args) throws UnsupportedEncodingException,
SocketException {
System.out.println("service start." + "");
StringBuffer response = new StringBuffer("");
response.append("<p>from <B>HTTP Service</B> response .<br/></p>");
HttpPoolService hs = new HttpPoolService(3333);
hs.registerRequest("/ccl", response.toString());
hs.registerRequest("/hs", response.toString());
hs.registerRequest("/hr", response.toString());
hs.start();// start Executor
}
}
请求处理:
package com.ccl.http;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.logging.Logger;
public class HandleRequest extends Thread {
private final Socket s;
private final Hashtable<String, String> knownRequests;
private final Logger log;
private final String C_R_L_E = "\r\n";
public HandleRequest(Socket s, Hashtable<String, String> knownRequests,
Logger log) {
this.s = s;
this.log = log;
this.knownRequests = knownRequests;// key is ccl
// start();
}
/**
* append host -> host
*
* @return
*/
public String getSocketInfo() {
StringBuffer sb = new StringBuffer();
if (s == null) {
return "";
}
sb.append("client:" + s.getInetAddress().getHostAddress()).append(":")
.append(s.getPort()).append(" -> ").append("service:")
.append(s.getLocalAddress().getHostAddress()).append(":")
.append(s.getLocalPort());
return sb.toString();
}
private void response(DataOutputStream ds, String code, String object,
boolean b, String info) {
try {
log.info("DataOutputStream:" + ds.size() + "code:" + code + "info:"
+ info);
ds.write((code + this.C_R_L_E).getBytes());
ds.write(("service:MiniHttpService/" + this.C_R_L_E).getBytes());
ds.write(("Connection:close " + this.C_R_L_E).getBytes());
if (null != object)
ds.write((object + C_R_L_E).getBytes());
if (b)
ds.write((C_R_L_E + "<html><head><title>" + code
+ "</title></head><body>"
+ "<h2>this is HttpService </h2><p>" + code + "</p><p>"
+ info + "</p></body></html>").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
BufferedReader br = null;
DataOutputStream ds = null;
String request = "";
boolean first = true;
try {
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
ds = new DataOutputStream(s.getOutputStream());
request = br.readLine();// 1 line
System.out.println("request:" + request);
String head;
while (true) {
head = br.readLine();// 2...n line
System.out.println("receive head is '" + head + "'");
if (head == null || head.trim().length() < 1) {
System.out.println("the head end.");
break;
}
}
System.out.println("*****************" + this.getSocketInfo());
if (request == null) {
log.info("request is null");
String info = "empty request ignored " + getSocketInfo();
response(ds, "HTTP/1.1 400 bad Request", null, true, info);
System.out.println(info);
return;
}
first = false;
System.out.println("Handling client request '" + request + " '\n");
/*
* String array[] = request.split(" "); for (String s : array)
* System.out.println("array[]:" + s);
*/
StringTokenizer toks = new StringTokenizer(request);
/***
* where request illegal ;when the request is legal.eg.
* http://127.0.0.1:port/ccl
*/
if (toks.countTokens() != 3) {
String msg = "wrong client syntax request " + request
+ ", cloing " + getSocketInfo() + " connection.";
response(ds, "HTTP/1.1 bad request", null, true, msg);
System.out.println("msg: " + msg);
return;
}
String method = toks.nextToken();// GET
String resource = toks.nextToken();// ccl
String version = toks.nextToken();// HTTP/1.1
/*** where method illegal */
// 501
if (!method.equalsIgnoreCase("GET")
&& !method.equalsIgnoreCase("HEAD")) {
String info = "invalid method in client " + getSocketInfo()
+ "request is '" + request + " '";
response(ds, "HTTP/1.1 501 Mthod not implemented ", null, true,
info);
System.out.println(info + version);
return;
}
String responseInfo = (String) knownRequests.get(resource).trim();
/* 404 */
if (responseInfo == null) {
String info = "Ignoring unknown data '" + resource.trim()
+ "' from client " + getSocketInfo() + " request is '"
+ request + " '";
response(ds, "HTTP/1.1 404 not Found Resource ", null, true,
info);
System.out.println(info);
return;
}
// success
response(ds, "HTTP/1.1 200 success ", null, true, getSocketInfo());
String length = "Content-Length: " + responseInfo.length();
ds.write((length + this.C_R_L_E).getBytes());
// Content-Type
ds.write(("Content-Type:text/plain;charset=ISO-8859-1" + this.C_R_L_E)
.getBytes());
// method = get
if (!method.equalsIgnoreCase("HEAD")) {
ds.write(C_R_L_E.getBytes());
ds.write(responseInfo.getBytes());
ds.flush();
}
} catch (IOException e) {
if (request == null && first) {
System.out.println("Ignoring connection/disconnnect attempt.");
} else {
System.out.println("problems with sending response for '"
+ request + "' to client " + getSocketInfo() + ": "
+ e.toString());
}
e.printStackTrace();
} finally {
try {
if (ds != null) {
ds.close();
ds = null;
}
if (br != null) {
br.close();
br = null;
}
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
test: