alp*_*ric 3 python sockets tcpserver socketserver
在三个迭代中的每一个都需要启动 TCPServer,然后立即停止。所有 3 次都需要在端口 8000 上启动。
正如它在下面的代码中定义的那样,TCPServer 启动。但它仅在第一次迭代期间开始。其他两个迭代无法启动 TCPServer,因为端口 8000 已被在先前(第一次)迭代中启动的 TCPServer 使用。为确保端口 8000 可用,需要关闭先前启动的 TCP 服务器。
如何终止(停止)已经运行的 TCPServer?
import SimpleHTTPServer
import SocketServer
def startServer():
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
Handler.extensions_map.update({'.webapp': 'application/x-web-app-manifest+json', })
try:
httpd = SocketServer.TCPServer(("", 8000), Handler)
httpd.serve_forever()
print('httpd server has been successfully started ')
except Exception, e:
print(e)
for i in range(3):
startServer()
Run Code Online (Sandbox Code Playgroud)
使用shutdown()告诉serve_forever()循环停止并等待它停止。2.6 版中的新功能。docs.python.org/2/library/socketserver.html
对于您的代码,它应该像
httpd.serve_forever()
print('httpd server has been successfully started ')
httpd.shutdown()
httpd.server_close()
print('httpd server has been successfully stopped')
Run Code Online (Sandbox Code Playgroud)
我将把它留给 OP,以便更好地使用它以及链接页面底部的示例,以满足所需的要求。
| 归档时间: |
|
| 查看次数: |
2529 次 |
| 最近记录: |