Unix 套接字编程:服务器关闭后端口未解除绑定
我正在学习 Unix 套接字编程。我制作了一个发送原始时间数据的时间服务器和一个接收该数据并将其转换为本地时间的客户端。
当我运行服务器时,将客户端连接到它(这会导致它们都完成工作并关闭),然后重新运行服务器,我在 bind() 调用上得到 errno = 98 。我必须更改服务器源代码中的端口并重新编译它以消除该错误。当我运行服务器并再次连接到它时,一切正常,在另一次重新运行后,情况又会重复。但我可以改回以前的端口。因此,每次调试运行时,我都会从端口 1025 跳到 1026,反之亦然(这种情况非常频繁,所以这有点烦人)。
它的工作原理如下:服务器打开侦听器套接字,绑定到它,侦听它,接受数据套接字的连接,向其中写入 time_t,关闭数据套接字,然后关闭侦听器套接字。客户端打开套接字,连接到服务器,读取数据并关闭套接字。
有什么问题吗?
提前致谢。
I'm studying Unix sockets programming. I made a time server that sends raw time data and a client for it that receives that data and converts it to local time.
When I run the server, connect a client to it (which causes both of them to do their job and shutdown) and then rerun the server, I get errno = 98 on bind() call. I have to change the port in the server's source code and recompile it to get rid of that error. When I run the server and connect to it again it's ok, after another rerun the situation repeats. But I can change back to previous port then. So I'm jumping from port 1025 to 1026 and vice-versa each debug run (which are very frequent, so this annoys a little).
It works like this: The server opens the listener socket, binds to it, listens to it, accepts a connection into a data socket, writes a time_t to it, closes the data socket and then closes the listener socket. The client opens a socket, connects to a server, reads data and closes the socket.
What's the problem?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
套接字关闭后会有一段延迟时间。在执行您的应用程序后,他们可能会保留占用的端口一段时间,以便他们可以发送任何未发送的数据。如果您等待足够长的时间,端口将被释放,并且可以再次被另一个套接字占用。
有关套接字延迟的更多信息,请查看:
http://www .developerweb.net/forum/archive/index.php/t-2982.html
The sockets have a lingering time after they close. They may keep the port taken for a litte while after the execution of your application, so they may send any unsent data. If you wait long enough the port will be released and can be taken again for another socket.
For more info on Socket Lingering check out:
http://www.developerweb.net/forum/archive/index.php/t-2982.html
setsockopt 和 SO_REUSEADDR
setsockopt and SO_REUSEADDR
查看
SO_REUSEADDR
Beej 的网络编程指南
Look into
SO_REUSEADDR
Beej's guide to network programming
有关导致此问题的原因的更多详细信息:
http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html
More details on what causes this:
http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html