我在我的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)
这意味着该选项发生在SocketO对象L级别的SOCKET(与TCP或其他东西相反),并且您正在设置SocketO选项REUSEADDR(您告诉操作系统这没问题,您真的想在这里听)。最后,使用1
打开该选项,而不是关闭(使用0
)。