我正在创建一个多线程服务器程序,以在尝试连接到 localhost 时显示浏览器的请求。
我发现我的 Windows 上只有 IE9 可以正常工作,但 Firefox 19、Chrome、Opera 却没有。他们只是坐在那里等待我的程序响应。
我错过了什么?
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HTTPEchoServer {
private static final String serverName = "HTTPEchoServer";
private static final int port = 80;
private static final String CRLF = "\r\n";
private static final Logger logger = Logger.getLogger(serverName);
private static void printHeader(PrintWriter out) {
out.println("HTTP/1.0 200 OK\r\n" + "Server: " + serverName + CRLF
+ "Content-Type: text/html" + CRLF + CRLF
+ "<!DOCTYPE HTML PUBLIC "
+ "\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
+ "<HTML>\n"
+ "<HEAD>\n"
+ " <TITLE>" + "HTTP Echo Server Result</TITLE>\n"
+ "</HEAD>\n"
+ "<H1>HTML Received from HTTP Echo Server</H1>\n"
+ "<B>Here is the request sent by your browser:</B>\n"
+ "<PRE>");
}
private static void printTrailer(PrintWriter out) {
out.println("</PRE>\n" + "</BODY>\n" + "</HTML>\n");
}
static class ClientHandler extends Thread {
Socket socket = null;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
logger.log(Level.INFO, "Accepted client {0}:{1}",
new Object[]{socket.getInetAddress(), socket.getPort()});
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
try (PrintWriter writer = new PrintWriter(os, true)) {
synchronized (this) {
printHeader(writer);
writer.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
writer.flush();
}
printTrailer(writer);
writer.flush();
writer.close();
}
}
socket.close();
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
logger.log(Level.INFO, "Disconnected client {0}:{1}",
new Object[]{socket.getInetAddress(), socket.getPort()});
}
}
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(port);
logger.log(Level.INFO, "Server started, listening at port {0} ...", port);
ExecutorService executor = Executors.newCachedThreadPool();
while (true) {
Socket socket = server.accept();
ClientHandler handler = new ClientHandler(socket);
executor.execute(handler);
}
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
另外,我发现除非我将端口更改为 8080,否则我无法在 OS X 上运行此程序。我已经在我的 OS X 10.8.2 计算机上禁用了防火墙。我得到的错误是:
<pre>
java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at HTTPEcho.HTTPEchoServer.main(HTTPEchoServer.java:80)
</pre>