我对TCP/IP网络上的客户端套接字有疑问.假设我使用
I have a question regarding client socket on TCP/IP network. Let's say I use
try: comSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: comSocket.bind(('', 5555)) comSocket.connect() except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2)创建的套接字将绑定到端口5555.问题在于结束连接后
The socket created will be bound to port 5555. The problem is that after ending the connection
comSocket.shutdown(1) comSocket.close()使用wireshark,我看到套接字从两侧用FIN,ACK和ACK闭合,我无法再使用该端口.我收到以下错误:
Using wireshark, I see the socket closed with FIN,ACK and ACK from both sides, I can't use the port again. I get the following error:
[ERROR] Address already in use我想知道如何立即清除端口,以便下次仍可以使用该端口.
I wonder how can I clear the port right away so that next time I still can use that same port.
comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)setsockopt似乎无法解决问题 谢谢!
setsockopt doesn't seem to be able to resolve the problem Thank you!
推荐答案在绑定套接字之前尝试使用SO_REUSEADDR套接字选项.
Try using the SO_REUSEADDR socket option before binding the socket.
comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)修改: 我看到您仍然对此感到麻烦.在某些情况下,SO_REUSEADDR将不起作用.如果尝试绑定套接字并重新连接到相同的目的地(启用SO_REUSEADDR),则TIME_WAIT仍然有效.但是,它将允许您连接到其他主机:端口.
I see you're still having trouble with this. There is a case where SO_REUSEADDR won't work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR enabled), then TIME_WAIT will still be in effect. It will however allow you to connect to a different host:port.
想到了几种解决方案.您可以继续重试,直到可以重新获得连接为止.或者,如果客户端启动套接字(而不是服务器)的关闭,那么它应该可以神奇地工作.
A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.
更多推荐
Python:绑定套接字:“地址已在使用中"
发布评论