我想在一个python程序中创建3个SocketServer:
import threading
import SimpleHTTPServer
import SocketServer
class PolicyHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(128).strip()
print self.data
if self.data == '<policy-file-request/>\0':
self.request.sendall('message 1')
class LiveRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.request.sendall('message 2')
def main():
httpd = SocketServer.TCPServer(('',80),\
SimpleHTTPServer.SimpleHTTPRequestHandler)
httpdThr = threading.Thread(target=httpd.serve_forever)
httpdThr.daemon = True
httpdThr.start()
liveServer = SocketServer.TCPServer(('',8090), LiveRequestHandler)
livThr = threading.Thread(target=liveServer.serve_forever)
livThr.daemon = True
livThr.start()
policyServer = SocketServer.TCPServer(('',834), PolicyHandler)
policyThr = threading.Thread(target=policyServer.serve_forever)
policyThr.daemon = True
policyThr.start()
if __name__ == '__main__':
main()
我运行它,输出如下:
Finding files... done.
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
奇怪的是它立即退出程序,所以我的客户程序不能 连接到三个套接字服务器。如何防止它退出程序?
答案 0 :(得分:0)
如果你真的想从同一个程序启动这三个服务器,那将是一个解决方案。
答案 1 :(得分:0)
现在我更改我的代码如下:
httpd = SocketServer.TCPServer(('',80), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpdThr = threading.Thread(target=httpd.serve_forever)
httpdThr.daemon = True
httpdThr.start()
liveServer = SocketServer.TCPServer(('',8090), LiveRequestHandler)
livThr = threading.Thread(target=liveServer.serve_forever)
livThr.daemon = True
livThr.start()
policyServer = SocketServer.TCPServer(('',834), PolicyHandler)
policyThr = threading.Thread(target=policyServer.serve_forever)
policyThr.daemon = True
policyThr.start()
它工作正常。但现在我不知道如何在需要时向客户发送消息。
答案 2 :(得分:0)
守护程序线程在没有更多非守护程序线程运行时终止,因此它们在主结束时退出。添加一些东西以保持主要运行,例如:
raw_input('Press enter to stop servers.')