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
def echo(socket, address):
print ('New connection from %s:%s' % address)
socket.sendall('Welcome to the echo server! Type quit to exit.\r\n')
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__':
server = StreamServer(('0.0.0.0', 6000), echo)
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)
server.start()
, 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?