如何避免java.net.BindException:地址已在使用中

如何避免java.net.BindException:地址已在使用中,java,linux,networking,tcp,Java,Linux,Networking,Tcp,以下设备运行了1小时,然后关闭: public class Mp extends JWindow implements MouseListener, MouseMotionListener { public static Mp j; private int serverPort = 0; private ServerSocket serverSock = null; private Socket sock = null; public static void main

以下设备运行了1小时,然后关闭:

public class Mp extends JWindow implements MouseListener, MouseMotionListener {
    public static Mp j;
  private int serverPort = 0;
  private ServerSocket serverSock = null;
  private Socket sock = null; 

  public static void main(final String[] args) throws IOException, InterruptedException, Exception {
    j = new Mp();
    j.setVisible(true);
    j.waitForConnections();
  }

  public void waitForConnections() {
    while (true) {
      try {
        sock = serverSock.accept();
        System.out.println("[TCPMediaHandler]: Accepted new socket");
        TCPMediaHandler handler = new TCPMediaHandler(sock);
        handler.start();
      } catch (IOException e) {
        e.printStackTrace(System.err);
      }
    }
  }

  public Mp() throws IOException {
    this.serverPort = 38891;
    serverSock = new ServerSocket(serverPort);
    serverSock.setReuseAddress(true);
    //serverSock.setSoTimeout(500);
    //serverSock.setSoLinger(true, 0);
    System.out.println("[TCPMediaHandler]: Server started");      
        this.v1.setBackground(Color.BLACK);
    this.v1.addMouseListener(this);
    /* Close the window */
    this.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
          System.exit(0); 
        }
      });
  }
当我重新运行相同的东西时,它会失败,出现
java.net.BindException

$ java -cp /var/tmp/dist/Mp.jar test.Mp
Exception in thread "main" java.net.BindException: Address already in use
    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:353)
    at java.net.ServerSocket.bind(ServerSocket.java:336)
    at java.net.ServerSocket.<init>(ServerSocket.java:202)
    at java.net.ServerSocket.<init>(ServerSocket.java:114)
    at test.Mp.<init>(Mp.java)
    at test.Mp.main(Mp.java)

您将看到您的setReuseAddress(true)被调用得太晚,即在绑定抛出异常之后

您可以通过三个步骤创建一个未绑定的ServerSocket,使其可重用,然后绑定它

ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345));

我的一个程序中也有类似的问题,但最终我只是从IDE中运行了一个程序实例,我没有注意到。始终仔细检查后台没有运行任何东西

谢谢大家!!我已经按照你的建议试过了。但我仍然无法修复它。请参见上面我的编辑跟进部分。现在仍然有一些显示,但实际上我没有,甚至我的申请也被终止了。但是我仍然可以执行
telnet localhost thatport
@YumYumYum如果端口处于关闭等待状态,则表明在获取该netstat时应用程序仍在运行。在我的场景中,我并不真正关心端口号,因此可以使用ServerSocket myServer=new ServerSocket(0);final int-port=myServer.getLocalPort()@tobi42在这种情况下,您将不会重用端口,因此不会出现问题。
ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345));