pythonpython-3.xtcpgeventgreenlets

Server in gevent and other greenlets in the same app


I'm searching how to run server in gevent and other greenlets in one program. So I want to have server (multiple connections) and one or two other greenlets. Is this possible? If yes, then how?

Best regards, Matt.


Solution

  • from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
    import gevent
    
    class EchoApplication(WebSocketApplication):
        def on_open(self):
            print ("Connection opened")
    
        def on_message(self, message):
            self.ws.send(message)
    
        def on_close(self, reason):
            print (reason)
    
    def _test():
        while True:
            gevent.sleep(1)
            print ('other greenlet')
    
    gevent.spawn(_test)
    
    WebSocketServer(
    ('', 9007),
    Resource({'/': EchoApplication})
    ).serve_forever()
    

    this code is serving ws server and printing 'other greenlet' text :)