在java中调用close()方法后,操作系统关闭socket需要多长时间? [英] How long does it take for the OS to close the socket after calling close() method in java?

查看:31
本文介绍了在java中调用close()方法后,操作系统关闭socket需要多长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 进行一些网络编程.在循环中我打开一个套接字,发送一些数据并关闭它.但我得到了连接已在使用中"的例外.我猜这是因为我在每次循环重复时使用相同的端口.操作系统(Ubuntu 11.10)关闭套接字并释放端口需要多长时间?谢谢

I'm doing some network programming in Java. in a loop I open a socket , send some data and close it. but I get the exception of "connection already in use" . I guess that happens since I use a same port at each repetition of the loop. how long does it take for the OS (Ubuntu 11.10) to close the socket and free the port? thanks

简化代码如下

while(true){
            Socket clientSocket = new Socket("localhost", 5000);
            PrintWriter outToServer = new PrintWriter( clientSocket.getOutputStream(),true);    
            outToServer.println ("Hi") ;
            clientSocket.close();   
        }

推荐答案

这可能需要很长时间(例如,如果有未发送的数据,则最多 3 分钟)

It can take quite a while (e.g. up to 3 minutes if there is unsent data)

在您的情况下,您每次都使用不同的本地端口(相同的远程端口无关紧要),所以应该无关紧要.

In your case you are using a different local port (same remote port doesn't matter) each time so it shouldn't matter.

顺便说一句:创建一个新连接非常昂贵,我会尝试重复使用一个连接而不是每次都打开一个新连接.在上面的例子中,它可以快 1000 倍.;)

BTW: Creating a new connection is pretty expensive, I would try to re-use a connection rather than opening a new one each time. In the example above it could be as much as 1000x faster. ;)

这篇关于在java中调用close()方法后,操作系统关闭socket需要多长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆