【问题标题】:How to listen to port 80 by using Java Socket如何使用 Java Socket 监听 80 端口
【发布时间】:2018-10-19 21:02:28
【问题描述】:

我有一个服务器的 80 端口被 HTTP 事务占用。我想查看该端口的流量,并尝试使用套接字程序来监听该端口。

public Server(int serverPort) throws IOException {  
    super(serverPort);  
    try {  
        while (true) {  
            Socket socket = accept();  
            new ServerThread(socket);  
        }  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        close();
    }  
}  

// inner-class ServerThread  
class ServerThread extends Thread {  
    private Socket socket;  
    private BufferedReader in;  
    private PrintWriter out;  

    // Ready to conversation  
    public ServerThread(Socket s) throws IOException {  
        this.socket = s;  
        in = new BufferedReader(new InputStreamReader(socket  
                .getInputStream(), "UTF-8"));  
        out = new PrintWriter(socket.getOutputStream(), true);  
        start();  
    }  

    // Execute conversation  
    public void run() {  
        try {  

            // Communicate with client until "bye " received.  
            while (true) {  
                String line = in.readLine();  
                if (line == null || "".equals(line.trim())) {
                    break;  
                }  
                System.out.println("Received   message: " + line);  
                out.println(line);  
                out.flush();  
            }  

            out.close();  
            in.close();  
            socket.close();  

        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

}  

public static void main(String[] args) throws IOException {  
    new Server(80);  
} 

但是,当我运行那个 java 应用程序时,它显示了一个 BindException: Address already in use。

那么我应该如何处理我的代码并让它监听 80 端口,或者在 Java 中还有其他方法可以监听该端口吗?

【问题讨论】:

    标签: java sockets http tcp


    【解决方案1】:

    如果我对您的理解正确,您正在尝试嗅探正在传递到您的服务器的数据包。如果是这种情况,this 帖子中有一些答案。

    【讨论】:

    • 当然可以使用Wireshark,但是需要使用独立的java程序来自动显示结果。
    • 那里还有其他 cmets,一些简单的谷歌搜索将我带到了这个 jpcap.sourceforge.net 但正如你在帖子中看到的那样,他们推荐了其他库。
    • 谢谢你,我终于切换到了 Pcap4j。
    【解决方案2】:

    你在哪个服务器上运行它?

    这完全取决于您正在使用的服务器类型。例如,Tomcat 在 Server.xml 文件中具有它正在运行的端口类型。

    【讨论】:

    • 我有 Jetty 服务器在 8080 端口上运行,顺便说一句,我不想​​更改 Server.xml 文件,因为我的套接字程序是一个独立的程序,我不想对其他程序进行任何更改程序在 Jetty 上运行。
    【解决方案3】:

    在 Windows 中,您可以由管理员运行您的程序。在 Linux 中使用 root 用户。

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 1970-01-01
      • 2016-05-05
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多