我一直在尝试编写一个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()永远不会被执行,因为线程正在阻止它。
答案 0 :(得分:1)
在我看来,阻止执行的方法不是线程,而是q.get()
。它将监听Queue
,直到一个项可用,但由于它在运行客户端应用程序之前执行,因此没有任何内容被发布到队列中。也许您应该return q
而是在调用myApp.start()
后听取模块2中的队列?
答案 1 :(得分: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()