Example echoserver.pyΒΆ

 1#!/usr/bin/env python
 2"""Simple server that listens on port 16000 and echos back every input to the client.
 3
 4Connect to it with:
 5  telnet 127.0.0.1 16000
 6
 7Terminate the connection by terminating telnet (typically Ctrl-] and then 'quit').
 8"""
 9from __future__ import print_function
10from gevent.server import StreamServer
11
12
13# this handler will be run for each incoming connection in a dedicated greenlet
14def echo(socket, address):
15    print('New connection from %s:%s' % address)
16    socket.sendall(b'Welcome to the echo server! Type quit to exit.\r\n')
17    # using a makefile because we want to use readline()
18    rfileobj = socket.makefile(mode='rb')
19    while True:
20        line = rfileobj.readline()
21        if not line:
22            print("client disconnected")
23            break
24        if line.strip().lower() == b'quit':
25            print("client quit")
26            break
27        socket.sendall(line)
28        print("echoed %r" % line)
29    rfileobj.close()
30
31if __name__ == '__main__':
32    # to make the server use SSL, pass certfile and keyfile arguments to the constructor
33    server = StreamServer(('127.0.0.1', 16000), echo)
34    # to start the server asynchronously, use its start() method;
35    # we use blocking serve_forever() here because we have no other jobs
36    print('Starting echo server on port 16000')
37    server.serve_forever()

Current source

Next page: Example geventsendfile.py