Java:重用具有不同IP的绑定套接字?

发布于 2024-12-04 10:16:27 字数 534 浏览 2 评论 0原文

我想做类似的事情:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云雾 2024-12-11 10:16:27

这不是 setReuseAddress 的用途。该函数对应于经典的 SO_REUSEADDR ,它与重用其他进程最近监听的端口有关。

Java 中没有办法做你想做的事。

That's not what setReuseAddress is for. That function corresponds to the classic SO_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.

许仙没带伞 2024-12-11 10:16:27

这也不是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文