我在eclipse中把服务打开后,在ie中输入http://localhost:8888却始终连不上去,这是怎么回事啊,以下是代码
import java.net.*;
import java.io.*;
import java.util.*;//类HttpServer从这里开始
public class HttpServer extends Thread {
// 继承自Thread,类HttpServer实现的Run()方法作为Http服务器的主控线程
// Http服务器的端口
private final int HTTP_PORT;
// ServerSocket, 服务器通过这个ServerSocket接收来自Web客户的连接请求
private ServerSocket listen = null;
// 布尔变量,指示是否要继续运行
private boolean running = true;
// 客户的请求和对相应请求的应答列表
private Hashtable knownRequests = new Hashtable(); // 构造函数,有一个参数port,指示Http服务器所在的端口
public HttpServer(int port) {
this.HTTP_PORT = port;
// 错误处理,端口号应该是大于零的整数
if (this.HTTP_PORT <= 0) {
System.err.println("HttpServer not started, as -Port is "
+ this.HTTP_PORT);
return;
}
// 此处将信息输出的System.err中,处于醒目的目的,在某些控制台上可以看到红色的输出
System.err.println("Creating new HttpServer on Port = "
+ this.HTTP_PORT);
// 设置主线程为精灵线程
setDaemon(true);
// 开始主控线程运行,此后可以接收来自客户的请求并处理
start();
} // 注册urlPath和data对,服务器从knowRequest表中匹配客户端的请求
// 并将匹配的内容返回客户端
public void registerRequest(String urlPath, String data) {
System.out.println("Registering urlPath: " + urlPath + "=" + data);
knownRequests.put(urlPath.trim(), data);
} public void removeRequest(String urlPath) {
knownRequests.remove(urlPath.trim());
} // 实现父类Thread的run方法
public void run() {
try {
// 创建ServerSocket的实例,ServerSocket绑定到HTTP_PORT端口
this.listen = new ServerSocket(HTTP_PORT);
// 如果running标志为true,那么继续运行,否则主服务线程退出,服务结束
while (running) {
// 接收来自客户端的TCP连接
Socket accept = this.listen.accept();
System.out.println("New incoming request on Port=" + HTTP_PORT
+ " ...");
if (!running) {
System.out.println("Closing http server Port=" + HTTP_PORT
+ ".");
break;
}
// 创建一个服务线程,为这个连接服务
// 为了同时为多个WEB客户服务,不能在这里就为客户服务
// 创建类HandlerRequest的实例,HandlerRequest也是Thread类的子类
// HandlerRequset为accept所代表的客户端与本地的TCP连接服务
// 当HandlerRequest向客户端发回响应后,它所创建的线程也将结束
HandleRequest hh = new HandleRequest(accept, knownRequests);
}
// 处理在服务过程中发生的异常
} catch (java.net.BindException e) {
System.out.println("HTTP server problem, Port "
+ listen.getInetAddress().toString() + ":" + HTTP_PORT
+ " is not available: " + e.toString());
} catch (java.net.SocketException e) {
System.out
.println("Socket " + listen.getInetAddress().toString()
+ ":" + HTTP_PORT + " closed successfully: "
+ e.toString());
} catch (IOException e) {
System.out.println("HTTP server problem on port : " + HTTP_PORT
+ ": " + e.toString());
}
// 主循环结束,线程将要退出,做清扫工作
if (this.listen != null) {
try {
// 关闭套接字
this.listen.close();
} catch (java.io.IOException e) {
System.out.println("this.listen.close()" + e.toString());
}
this.listen = null;
}
} // 可以调用这个方法停止HttpServer的服务
public void shutdown() {
System.out.println("Entering shutdown");
// 设置标志,通知主服务线程不再为新连接服务
running = false;
try {
// 关闭套接字
if (this.listen != null) {
this.listen.close();
this.listen = null;
}
} catch (java.io.IOException e) {
System.out.println("shutdown problem: " + e.toString());
}
} // 主程序的入口
public static void main(String[] args) {
// 创建一个HttpServer的实例,使用8888端口
HttpServer server = new HttpServer(8888);
// 当客户端请求的url是”/Hello”时,返回”Hello World from MiniHttpServer!”
server.registerRequest("/Hello", "Hello World from MiniHttpServer!");
// 按任意建退出程序
System.out.println("Press any key to exit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}class HandleRequest extends Thread {
// socket,服务器accept的套接字
private final Socket sock;
private final Hashtable knownRequests;
private final String CRLF = "\r\n"; public HandleRequest(Socket sock, Hashtable knownRequests) {
this.sock = sock;
this.knownRequests = knownRequests;
// 开始线程,为来自客户端的请求服务
start();
} // 继承自Thread类的run()方法
public void run() {
System.out.println("Handling client request,...");
BufferedReader iStream = null;
DataOutputStream oStream = null;
String clientRequest = "";
boolean first = true;
try {
// 从socket中获取输入、输出流
iStream = new BufferedReader(new InputStreamReader(sock
.getInputStream()));
oStream = new DataOutputStream(sock.getOutputStream());
// 从客户端读取请求信息
clientRequest = iStream.readLine();
String headerLine;
while (true /* !sock.isClosed() JDK 1.4 only */) {
// 读取HTTP请求的首部信息
headerLine = iStream.readLine();
System.out.println("Receiving header '" + headerLine + "'");
if (headerLine == null || headerLine.trim().length() < 1) {
break;
}
}
System.out.println("Request from client " + getSocketInfo());
if (clientRequest == null) {
String info = "Empty request ignored " + getSocketInfo();
errorResponse(oStream, "HTTP/1.1 400 Bad Request", null, true,
info);
System.out.println(info);
return;
}
first = false;
System.out.println("Handling client request '" + clientRequest
+ "' ...");
StringTokenizer toks = new StringTokenizer(clientRequest);
// 一个请求字符串由三部分组成,例如“GET /Hello HTTP/1.0”
if (toks.countTokens() != 3) {
String info = "Wrong syntax in client request: '"
+ clientRequest + "', closing " + getSocketInfo()
+ " connection.";
errorResponse(oStream, "HTTP/1.1 400 Bad Request", null, true,
info);
System.out.println(info);
return;
}
String method = toks.nextToken(); // "GET"
String resource = toks.nextToken(); // "/Hello"
String version = toks.nextToken(); // "HTTP/1.0"
// 作为简易的HTTP服务器,只处理GET和HEAD
if (!method.equalsIgnoreCase("GET")
&& !method.equalsIgnoreCase("HEAD")) {
String info = "Invalid method in client " + getSocketInfo()
+ " request: '" + clientRequest + "'";
errorResponse(oStream, "HTTP/1.1 501 Method Not Implemented",
"Allow: GET", true, info);
System.out.println(info);
return;
}
// 从knownRequest列表中查找响应字符串
String responseStr = (String) knownRequests.get(resource.trim());
// 没有找到,生成错误信息
if (responseStr == null) {
String info = "Ignoring unknown data '" + resource.trim()
+ "' from client " + getSocketInfo() + " request: '"
+ clientRequest + "'";
errorResponse(oStream, "HTTP/1.1 404 Not Found", null, true,
info);
System.out.println(info);
return;
}
// 发会服务成功的状态
errorResponse(oStream, "HTTP/1.1 200 OK", null, false, null);
// 生成首部域Content-Length
String length = "Content-Length: " + responseStr.length();
oStream.write((length + CRLF).getBytes());
// 生成Content-Type首部域
oStream
.write(("Content-Type: text/plain; charset=iso-8859-1" + CRLF)
.getBytes());
if (!method.equalsIgnoreCase("HEAD")) {
oStream.write(CRLF.getBytes());
oStream.write(responseStr.getBytes());
}
oStream.flush();
// 处理异常
} catch (IOException e) {
if (clientRequest == null && first) {
System.out.println("Ignoring connect/disconnect attempt");
} else {
System.out.println("Problems with sending response for '"
+ clientRequest + "' to client " + getSocketInfo()
+ ": " + e.toString());
}
} finally {
try {
if (iStream != null)
iStream.close();
} catch (IOException e) {
}
try {
if (oStream != null)
oStream.close();
} catch (IOException e) {
}
try {
sock.close();
} catch (IOException e) {
}
}
} // 调用此方法向oStream写回相应信息
// 参数body指示是否在响应信息中加入在浏览器中显示的超文本页面内容提示作为错误
private void errorResponse(DataOutputStream oStream, String code,
String extra, boolean body, String info) throws IOException {
oStream.write((code + CRLF).getBytes());
oStream.write(("Server: MiniHttpServer/" + CRLF).getBytes());
if (extra != null)
oStream.write((extra + CRLF).getBytes());
oStream.write(("Connection: close" + CRLF).getBytes());
if (body) {
// 写入可以在浏览器中显示的超文本错误信息
oStream
.write((CRLF + "<html><head><title>" + code
+ "</title></head><body>" + "<h2>MiniHTTP server "
+ "</h2>" + "<p>" + code + "</p>" + "<p>" + info
+ "</p>" + "</body></html>").getBytes());
}
} // 返回关于Socket的信息
private String getSocketInfo() {
StringBuffer sb = new StringBuffer(196);
if (sock == null)
return "";
sb.append(sock.getInetAddress().getHostAddress());
sb.append(":").append(sock.getPort());
sb.append(" -> ");
sb.append(sock.getLocalAddress().getHostAddress());
sb.append(":").append(sock.getLocalPort());
return sb.toString();
}
}