我在我的 python 程序中使用了一个端口并关闭了它,现在我想再次使用它。只是那个端口而不是另一个端口。
有没有办法强制操作系统使用 python 释放端口?
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12349
portt = 12341 # Reserve a port for your service.
s.bind((host, portt)) # Bind to the port
s.connect((host, port))
s.close
ss = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
ss.bind((host, portt))
s.close
但是输出是:
Traceback (most recent call last):
File "client.py", line 17, in <module>
ss.bind((host, portt))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
请您参考如下方法:
您永远无法强制操作系统(通过任何合理的努力)释放套接字。
相反,您只想说您不关心 setsockopt
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
这意味着该选项发生在 Socket Object Level SOCKET(与 TCP 或其他东西相反)并且您正在设置 Socket Option REUSEADDR(您是在告诉操作系统没问题,您真的很想在这里听)。最后,您使用 1 打开选项,而不是关闭(使用 0)。
