Java:重用具有不同IP的绑定套接字?
我想做类似的事情:
public void myFun (String tIps [])
{
Socket s = new Socket ();
s.connect (new InetSocketAddress (serverIp, 80), 1000);
for (int i = 0 ; i < tIps.length ; ++i)
{
// Rebind the socket with another Ip
s.bind (new InetSocketAddress (tIps [i], 0));
/*
* use the socket
*/
}
s.close ()
}
但我收到此错误:“java.net.SocketException:已绑定”。 我尝试使用 s.setReuseAddress(true),但它没有改变任何东西。 有没有解决方案可以避免为每个很长的请求打开一个新的套接字?
谢谢 !
I want to do something like that :
public void myFun (String tIps [])
{
Socket s = new Socket ();
s.connect (new InetSocketAddress (serverIp, 80), 1000);
for (int i = 0 ; i < tIps.length ; ++i)
{
// Rebind the socket with another Ip
s.bind (new InetSocketAddress (tIps [i], 0));
/*
* use the socket
*/
}
s.close ()
}
But I get this error : "java.net.SocketException: Already bound".
I tried to use s.setReuseAddress (true), but it did'nt change anything.
Is there any solution to avoid opening a new socket for each request, which is very long ?
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是
setReuseAddress
的用途。该函数对应于经典的 SO_REUSEADDR ,它与重用其他进程最近监听的端口有关。Java 中没有办法做你想做的事。
That's not what
setReuseAddress
is for. That function corresponds to the classicSO_REUSEADDR
, which is related to re-using a port that some other process has been listening on recently.There is no way in Java to do what you want.
这也不是
bind()
的用途。套接字已经连接到目标:之后更改本地出站接口有什么意义?只需完全省略绑定步骤即可。路由表将确定使用哪个本地接口来连接到目标。
That's not what
bind()
is for either. The socket is already connected to a target: what would be the point of changing the local outbound interface after that?Just omit the bind step altogether. The routing tables will figure out which local interface to use to connect to the target.