Search code examples
pythonblockinggevent

How can I keep multiple gevent servers serving forever?


Currently, I have an application that has two servers: the first processes orders and responds individually, the second broadcasts results to other interested subscribers. They need to be served from different ports. I can start() both of them, but I can only get one or the other to serve_forever() as I read it is a blocking function. I am looking for ideas on how to keep both the servers from exiting. abbreviated code below:

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

Perhaps I just need a way to keep the two from exiting, but I'm not sure how. In the end, I want both servers to listen forever for incoming connections and handle them.


Solution

  • ok, I was able to do this using threading and with gevent's monkeypatch library:

    from gevent import monkey
    def main():
        monkey.patch_thread()
    # etc, etc
    t = threading.Thread(target=bcastserver.serve_forever)
    t.setDaemon(True)
    t.start()
    tradeserver.serve_forever()