Java Socket Programming =>只有IE9有效吗?

时间:2013-02-26 10:02:20

标签: java sockets

我正在创建一个多线程服务器程序,以便在尝试连接到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);
        }
    }
}    

此外,我发现我无法在OS X上运行此程序,除非我将端口更改为8080.我已经在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>

3 个答案:

答案 0 :(得分:2)

除了MSIE之外,您无法在所有浏览器中的applet中打开服务器套接字。这样做是因为打开服务器套接字是安全违规。如果你想这样做,你必须签署你的小程序。

我希望我能正确理解你的代码是在applet环境中运行的(因为你提到过浏览器),虽然我看不到从main()开始的堆栈跟踪中的这个方面。

编辑: 我再次阅读你的帖子并理解你的问题实际上包含两个问题:第一个关于applets,第二个关于在Unix下运行作为应用程序。对于unix @Anders R. Bystrup给出了答案:只有root才能收听1024以下的端口。因此,您必须以root身份运行程序或使用sudo

似乎你走错了路。您是否可以解释一下您希望实现的目标,社区可能会为您提供更好的解决方案。

答案 1 :(得分:0)

正如异常本身所说java.net.BindException: Permission denied。您需要root用户绑定1024以下的端口。如果你在Linux上,你可以sudo java HTTPEchoServer启动服务器。

其他可能性是您已在端口80上运行服务器。

答案 2 :(得分:0)

端口80是保留的HTTP端口,还有其他端口也是保留的。

端口1到1023用于管理功能,使端口号大于1024可供使用。

How to find available port