Gevent StreamServer.start () doesn't seem to do what I expect

I'm trying to wrap my brain with concepts that gevent uses . Here is an example from the gentent code repository. This is a simple echo server.

from gevent.server import StreamServer

# this handler will be run for each incoming connection in a dedicated greenlet
def echo(socket, address):
    print ('New connection from %s:%s' % address)
    socket.sendall('Welcome to the echo server! Type quit to exit.\r\n')
    # using a makefile because we want to use readline()
    fileobj = socket.makefile()
    while True:
        line = fileobj.readline()
        if not line:
            print ("client disconnected")
            break
        if line.strip().lower() == 'quit':
            print ("client quit")
            break
        fileobj.write(line)
        fileobj.flush()
        print ("echoed %r" % line)


if __name__ == '__main__':
    # to make the server use SSL, pass certfile and keyfile arguments to the constructor
    server = StreamServer(('0.0.0.0', 6000), echo)
    # to start the server asynchronously, use its start() method;
    # we use blocking serve_forever() here because we have no other jobs
    print ('Starting echo server on port 6000')
    server.serve_forever()

It seems pretty simple, and I work it. However, as the comment says, it serve_forever()is a blocking function. If I changed the last line to server.start(), the program will stop after each line is executed once. I am doing something wrong, but the documentation is not very helpful.

The documentation section that implements servers with gevent says that use start()should spawn new greens for each new connection when using the following code:

 def handle(socket, address):
     print 'new connection!'

 server = StreamServer(('127.0.0.1', 1234), handle) # creates a new server
 server.start() # start accepting new connections

, The server_forever() method calls start() and then waits until interrupted or until the server is stopped. start(), , ?

:

  • start() serve_forever()?
  • ?
  • gevent.spawn() gevent.joinall() , - , StreamServer?
+5
1
  • start() - , . , .
  • serve_forever(). start() , - .
  • no, gevent.spawn() gevent.joinall() .

gevent 1.0 gevent.wait(), , ///.

: https://github.com/gevent/gevent/blob/master/examples/portforwarder.py

+9

All Articles