美文网首页
简单的让socketserver支持协程

简单的让socketserver支持协程

作者: xin激流勇进 | 来源:发表于2018-08-04 20:38 被阅读0次
    from socketserver import StreamRequestHandler
    from socketserver import TCPServer
    import gevent
    from gevent import monkey
    from time import ctime
    
    monkey.patch_all()
    HOST = ''
    PORT = 8888
    ADDR = (HOST, PORT)
    
    
    class GeventServer(TCPServer):
    
        def _handle_request_noblock(self):
            """Handle one request, without blocking.
    
            I assume that selector.select() has returned that the socket is
            readable before this function was called, so there should be no risk of
            blocking in get_request().
            """
            try:
                request, client_address = self.get_request()
            except OSError:
                return
            if self.verify_request(request, client_address):
                try:
                    gevent.spawn(self.process_request, request, client_address)
                except Exception:
                    self.handle_error(request, client_address)
                    self.shutdown_request(request)
                except:
                    self.shutdown_request(request)
                    raise
            else:
                self.shutdown_request(request)
    
    
    class MyRequestHandler(StreamRequestHandler):
    
        def handle(self):
            self.wfile.write('hello world\r\n'.encode())
            print('...connected from:', self.client_address)
            content = self.rfile.read()
            print(content)
            message = '[%s] %s' % (ctime(), content.decode())
            self.request.sendall(msg)
            print(self.request)
    
    
    tcpSev = GeventServer(ADDR, MyRequestHandler)
    tcpSev.serve_forever()
    
    

    相关文章

      网友评论

          本文标题:简单的让socketserver支持协程

          本文链接:https://www.haomeiwen.com/subject/flzmvftx.html