我在重复使用相同的地址时遇到 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)
Edit
我解决了 InvalidArgument 异常并且我已经编辑了上面的帖子但是现在在同一端口上重新连接时我得到了上面的异常。我做错了什么吗?
最佳答案
如果你想重复使用一个地址你必须调用setReuseAddress(true)在绑定(bind)套接字之前。
关于java.net.绑定(bind)异常 : Address already in use while re using same connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25643070/