4

我编写了一个简单的 tcp 服务器,gevent.StreamServer用于测试目的。为了让我向某些客户端发送响应,我需要一种非阻塞方式来处理通过 的输入raw_input(),最好不使用线程。

经过一番谷歌搜索后,我偶然发现了这个问题:How to make non-blocking raw_input when using eventlet.monkey_patch() 以及为什么它会阻塞所有内容,即使在另一个线程上执行也是如此?

我写了以下内容,它完全符合我的要求,但是我认为有更好的方法。有人能指出我正确的方向吗?此外,感谢 try/except 没有捕获 KeyboardInterrupt 的想法。

import select
from gevent.monkey import patch_all
from gevent.server import StreamServer

patch_all(os=True, select=True)

def raw_input(message):
    """ Non-blocking input from stdin. """
    sys.stdout.write(message)

    select.select([sys.stdin], [], [])
    return sys.stdin.readline()

def main():
    """ Run the server, listen for commands """

    server = StreamServer(("0.0.0.0", 6000), handle)
    print "Starting server"
    gevent.signal(signal.SIGTERM, server.close)
    gevent.signal(signal.SIGQUIT, server.close)
    gevent.signal(signal.SIGINT, server.close)

    server.start()
    while True:
        try:
            a = raw_input("")
            if a:
                print "Received %s" % a
            gevent.sleep(0)
        except KeyboardInterrupt:
            print "Received a shutdown signal, going down ..."
            server.stop()
            sys.exit(0)

if __name__ == "__main__":
    main()

编辑:我已经重写了部分代码,现在我明白了 main() 函数的愚蠢之处。如果有人偶然发现这个问题并且对如何做有更好的想法,我会将其发布为编辑。

from gevent.signal import signal

def get_console_input():
    """ Non-blocking console input to the server """

    select.select([sys.stdin], [], [])
    # There's quite a bit of code here but it is input handling so 
    # for shortness's sake   I've snipped everything and return the line read.
    return sys.stdin.readline()

def exit(server):
    """ Quit the server gracefully """

    print "Received shutdown signal, going down. """
    server.close()
    sys.exit(0)

def main():
    """ The main function. Create and run the server, listen for commands and
   append any command to the server so it can send them on to the clients """

    # Myserver is a class which inherits from gevent.server.StreamServer.
    # Myserver could just as well be replaced by gevent.server.StreamServer.

    server = MyServer(("0.0.0.0", PORT))
    print "Starting server"

    # Add some signal handlers to quit the server gracefully.
    gevent.signal(signal.SIGTERM, exit, server)
    gevent.signal(signal.SIGQUIT, exit, server)
    gevent.signal(signal.SIGINT, exit, server)

    # Server started in async mode
    server.start()

    while True:
        get_console_input()
        gevent.sleep(0)

if __name__ == "__main__":
    main()
4

1 回答 1

5

我发现这样做的最简单方法是使用gevent.socket.wait_read等待直到sys.stdin可以读取:

wait_read(sys.stdin.fileno())
return sys.stdin.readline()

我还围绕文件描述符编写了一个小包装器,以赋予它们非阻塞.read().write()方法:https ://gist.github.com/2915875

于 2012-06-12T07:27:23.670 回答