java.net.BindException:重新使用同一连接时,地址已在使用中

java.net.BindException:重新使用同一连接时,地址已在使用中,java,socket.io,nio,Java,Socket.io,Nio,重复使用同一地址时,我得到了BindException异常。下面是我的代码 在openConnection方法中: 69. Selector selector = SelectorProvider.provider().openSelector(); 70. SocketChannel socketChannel = SocketChannel.open(); 71. socketChannel.bind(new InetSocketAddress(port));// Edit

重复使用同一地址时,我得到了BindException异常。下面是我的代码

在openConnection方法中:

69.    Selector selector = SelectorProvider.provider().openSelector();
70.    SocketChannel socketChannel = SocketChannel.open();
71.    socketChannel.bind(new InetSocketAddress(port));// Edited
72.    socketChannel.socket().setReuseAddress(true);
73.    socketChannel.configureBlocking(false);
74.    socketChannel.connect(remoteAddress);
java.net.BindException: Address already in use
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:414)
at sun.nio.ch.Net.bind(Net.java:406)
at sun.nio.ch.SocketChannelImpl.bind(SocketChannelImpl.java:580)
at sun.nio.ch.SocketAdaptor.bind(SocketAdaptor.java:135)
at com.example.client.request.Client.openConnection(Client.java:72)
例外情况:

69.    Selector selector = SelectorProvider.provider().openSelector();
70.    SocketChannel socketChannel = SocketChannel.open();
71.    socketChannel.bind(new InetSocketAddress(port));// Edited
72.    socketChannel.socket().setReuseAddress(true);
73.    socketChannel.configureBlocking(false);
74.    socketChannel.connect(remoteAddress);
java.net.BindException: Address already in use
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:414)
at sun.nio.ch.Net.bind(Net.java:406)
at sun.nio.ch.SocketChannelImpl.bind(SocketChannelImpl.java:580)
at sun.nio.ch.SocketAdaptor.bind(SocketAdaptor.java:135)
at com.example.client.request.Client.openConnection(Client.java:72)
编辑


我解决了InvalidArgument异常,我编辑了上面的文章,但现在在同一端口重新连接时,我得到了上面的异常。我是否做错了什么?

表示尝试将套接字绑定到本地地址和端口时出错。通常,端口正在使用中,或者无法分配请求的本地地址

当您启动web服务器或应用程序服务器(通常在端口(例如Tomcat或Jetty)上侦听8080和8084上的HTTP和HTTPS流量)时,它们会将套接字绑定到本地地址和端口。如果您给他们主机名,例如localhost或devhost,那么他们在Windows和Linux中都使用/etc/host将域名解析为IP地址,如果此映射不正确,您将得到java.net.BindException:无法分配请求的地址:JVM\u Bind。此主机到IP地址映射文件可在C:\Windows\System32\Drivers\etc\hosts中找到,其中C:\Windows是您安装Windows操作系统的位置。如果查看此文件,您将看到它包含IP地址和主机名,如下所示:

127.0.0.1本地主机 192.168.52.1本地主机


只要更正映射,或针对localhost添加127.0.0.1,即可解决此问题。

如果要重用绑定套接字之前必须调用的地址。

在绑定()之后调用setReuseAddress()是徒劳的。必须提前打电话。但是根本不需要调用bind()。@EJP谢谢,将setReuseAddress()放在bind()之上解决了问题,我使用了bind,因为我想打开特定端口并重新使用它。请将您的评论放在回答中,我想将其标记为已回答。我确实尝试过使用127.0.0.1或localhost,但这只在我的本地pc连接到远程时才起作用。它给了我无效的参数异常。但是感谢您的解释,我解决了它并编辑了它邮报。