我需要关闭套接字吗? [英] Do I need to close a socket?

查看:63
本文介绍了我需要关闭套接字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Winsock 通过套接字发送数据后,您应该像这样关闭连接:

After sending data over a socket with Winsock, you're supposed to close the connection like this:

closesocket(ConnectSocket);
WSACleanup();

我正在编写一个通过套接字发送数据的 API.如果之后我必须关闭套接字,我需要向 API 添加一个函数,以便用户可以说他们何时完成获取数据.为方便起见,如果我不关闭套接字是否有问题?

I'm writing an API that sends data over a socket. If I have to close the socket afterwards, I need to add a function to the API so that users can say when they're done getting data. Is it a problem if I don't close the socket, for convenience?

推荐答案

无论如何,如果您不关闭套接字,您的程序将泄漏文件描述符.程序通常只能打开有限数量的文件描述符,所以如果这种情况经常发生,它可能会变成一个问题.

One way or another, if you don't close a socket, your program will leak a file descriptor. Programs can usually only open a limited number of file descriptors, so if this happens a lot, it may turn into a problem.

如果套接字绑定到一个地址,则在套接字关闭之前,没有其他套接字能够绑定到相同的地址.如果它绑定到一个众所周知的端口(例如 25 或 80),这将阻止其他任何东西绑定到该端口......这可能是您可能面临的最严重的问题.如果它绑定到一个临时端口,这不是那么重要,但是,仍然有数量有限的端口,如果这种情况经常发生,那么你可能会用完.需要注意的是,UDP sockets是可以自由使用的,从来没有被绑定过,所以这个问题可能不适用于UDP sockets.

If the socket is bound to an address, no other socket will be able to bind to the same address until the socket is closed. If it's bound to a well-known port (like 25, or 80, for example), this will prevent anything else from binding to that port... which would probably be the most serious problem you might face. If it's bound to an ephemeral port, this is not as important, but, still, there are a limited number of ports and if this happens a lot then you may run out. Note that UDP sockets can be used freely without ever being bound, so this problem may not apply to UDP sockets.

如果socket是一个监听socket(listen()已经在它上面被调用了),如果你不关闭它,系统将继续接受这个socket上的连接(但最多只能到listen() 中指定的 backlog 限制.

If the socket is a listening socket (listen() has been called on it), the system will continue to accept connections on this socket if you don't close it (but only up to the backlog limited specified in listen()).

如果套接字是 TCP 套接字并且已连接,则 TCP 连接不会关闭,除非套接字已关闭或 shutdown() 被调用.因此,在这种情况下,如果无法关闭套接字,您至少应该确保调用shutdown().

If the socket is a TCP socket and it is connected, then the TCP connection will not be closed unless the socket is closed or shutdown() is called. Therefore, in this case, you should at least make sure to call shutdown() if you can't close the socket.

总而言之,不关闭套接字可能会导致几个或多或少重要的问题.通常,TCP 的问题可能会比 UDP 多.使用完套接字后,如果可能,您一定要关闭它们!

In conclusion, not closing a socket may lead to several problems which are more or less important. Generally you can expect more problems with TCP than UDP. You should definitely close sockets if possible when you are done with them!

这篇关于我需要关闭套接字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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