【发布时间】:2014-09-03 11:24:16
【问题描述】:
我在重复使用相同的地址时遇到 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)
编辑
我解决了 InvalidArgument 异常,我已经编辑了上面的帖子,但现在在同一个端口上重新连接时,我得到了上面的异常。我做错了什么吗?
【问题讨论】:
-
调用 setReuseAddress() after bind() 是徒劳的。必须先调用它。但是根本不需要调用bind()。
-
@EJP 谢谢,通过将 setReuseAddress() 放在 bind() 上方解决了问题,我使用了 bind 因为我想打开特定端口并重用它。请将您的评论放在我想标记的答案中如已回答。