import gevent from gevent import Greenlet def my_func(i): gevent.sleep(i) print(f"Finished task {i}") for i in range(10): Greenlet.spawn(my_func, i)
import gevent from gevent.server import StreamServer def handle_connection(sock, address): print(f"New connection from {address}") while True: data = sock.recv(1024) if not data: break sock.sendall(data) sock.close() server = StreamServer(('localhost', 8000), handle_connection) print("Starting server...") server.serve_forever()In this example, we create a simple TCP server that listens on port 8000. When a new connection is received, the `handle_connection()` function is called in a green thread to handle the request. The `handle_connection()` function receives the socket and the address of the client, and reads data from the socket in a loop, sending it back to the client. The server runs indefinitely, handling multiple connections concurrently. Package library: gevent is a third-party library that can be installed using pip.