0

我想在一个 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

奇怪的是它立即退出程序,所以我的客户端程序无法连接到三套接字服务器。如何防止它退出程序?

4

3 回答 3

0

If you really want to start the three servers from the same program, that would be one solution.

于 2012-10-06T07:55:44.823 回答
0

当没有更多非守护线程运行时,守护线程终止,因此它们在主线程结束时退出。添加一些内容以保持 main 运行,例如:

raw_input('Press enter to stop servers.')
于 2012-10-06T16:58:23.570 回答
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()

它工作正常。但现在我不知道如何在需要时向客户端发送消息。

于 2012-10-06T13:11:14.027 回答