gpt4 book ai didi

python - 如何让多个 gevent 服务器永远服务?

转载 作者:行者123 更新时间:2023-11-30 23:34:04 24 4
gpt4 key购买 nike

目前,我的应用程序有两个服务器:第一个服务器处理订单并单独响应,第二个服务器将结果广播给其他感兴趣的订阅者。它们需要从不同的港口提供服务。我可以 start() 两者,但我只能将其中一个调用到serve_forever(),因为我读到它是一个阻塞函数。我正在寻找有关如何防止两台服务器退出的想法。缩写代码如下:

def main():
stacklist = []
subslist = []
stacklist.append(CreateStack('stuff'))
subslist.append(Subscription('stuff'))
bcastserver = BroadcastServer(subslist) # creates a new server
tradeserver = TradeServer(stacklist) # creates a new server
bcastserver.start() # start accepting new connections
tradeserver.start() # start accepting new connections
#bcastserver.serve_forever() #if I do it here, the first one...
#tradeserver.serve_forever() #blocks the second one

class TradeServer(StreamServer):
def __init__(self, stacklist):
self.stacklist = stacklist
StreamServer.__init__(self, ('localhost', 12345), self.handle)
#self.serve_forever() #If I put it here in both, neither works

def handle(self, socket, address):
#handler here

class BroadcastServer(StreamServer):
def __init__(self, subslist):
StreamServer.__init__(self, ('localhost', 8000), self.handle)
self.subslist = subslist
#self.serve_forever() #If I put it here in both, neither works

def handle(self, socket, address):
#handler here

也许我只是需要一种方法来防止两者退出,但我不确定如何做。最后,我希望两台服务器永远监听传入连接并处理它们。

最佳答案

我知道这个问题有一个公认的答案,但还有一个更好的答案。我添加它是为了像我这样稍后找到这篇文章的人。

gevent documentation about servers 中所述:

The BaseServer.serve_forever() method calls BaseServer.start() and then waits until interrupted or until the server is stopped.

所以你可以这样做:

def main():
stacklist = []
subslist = []
stacklist.append(CreateStack('stuff'))
subslist.append(Subscription('stuff'))
bcastserver = BroadcastServer(subslist) # creates a new server
tradeserver = TradeServer(stacklist) # creates a new server
bcastserver.start() # starts accepting bcast connections and returns
tradeserver.serve_forever() # starts accepting trade connections and blocks until tradeserver stops
bcastserver.stop() # stops also the bcast server

gevent introduction documentation解释了为什么它有效:

Unlike other network libraries, though in a similar fashion as eventlet, gevent starts the event loop implicitly in a dedicated greenlet. There’s no reactor that you must call a run() or dispatch() function on. When a function from gevent’s API wants to block, it obtains the gevent.hub.Hub instance — a special greenlet that runs the event loop — and switches to it (it is said that the greenlet yielded control to the Hub).

当serve_forever()阻塞时,它不会阻止任一服务器继续通信。

注意:在上面的代码中,交易服务器是决定整个应用程序何时停止的服务器。如果您希望广播服务器决定这一点,则应该在 start()serve_forever() 调用中交换它们。

关于python - 如何让多个 gevent 服务器永远服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18455467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com