1

我一直在尝试编写一个 python 脚本来启动一个线程来侦听套接字并将 HTTP 数据发送到另一个应用程序以由同一程序启动。在执行应用程序之前,需要运行套接字服务器。但是,运行套接字服务器的线程会阻止程序的进一步执行,并冻结它正在侦听的位置。放一些虚拟代码。

在模块 1 中:

def runServer(Port, Host, q):
    HTTPServerObj = HTTPServer((Host, Port), RequestHandler)
    HTTPServerObj.handle_request()
    HTTPServerObj.server_close()
    q.put((True, {'messageDoNotDuplicate': 'Data sent successfully by the server'}))

class SpoofHTTPServer(object):
    def runServerThread(self):
        q = Queue.Queue()
        serverThread=Thread(target=runServer, args=(self.Port, self.Host, q))
        serverThread.daemon=True
        serverThread.start()
        result = q.get()
        print result
        return result

在模块 2 中:

from module1 import SpoofHTTPServer

spoofHTTPServer = SpoofHTTPServer()
result = spoofHTTPServer.runServerThread()
rc = myApp.start()

myApp.start() 永远不会被执行,因为线程正在阻塞它。

4

2 回答 2

1

在我看来,阻止执行的方法不是线程,而是q.get(). 它会一直监听Queue直到一个项目可用,但由于它是在运行客户端应用程序之前执行的,所以没有任何东西被发布到队列中。也许您应该return q改为在调用后收听模块 2 中的队列myApp.start()

于 2013-07-10T17:12:21.613 回答
0

这可能适用于 Python 3。建立连接('localhost', 8080)以查看它的工作原理。

import queue as Queue
from threading import Thread
from http.server import HTTPServer
from socketserver import BaseRequestHandler as RequestHandler

def runServer(Port, Host, q):
    HTTPServerObj = HTTPServer((Host, Port), RequestHandler)
    HTTPServerObj.handle_request()
    HTTPServerObj.server_close()
    q.put((True, {'messageDoNotDuplicate':
                  'Data sent successfully by the server'}))

class SpoofHTTPServer(object):

    Port = 8080
    Host = ''

    def runServerThread(self):
        q = Queue.Queue()
        serverThread=Thread(target=runServer, args=(self.Port, self.Host, q))
        serverThread.daemon=True
        serverThread.start()
        result = q.get()
        print(result)
        return result

spoofHTTPServer = SpoofHTTPServer()
result = spoofHTTPServer.runServerThread()
##rc = myApp.start()
于 2013-07-10T17:51:30.483 回答