The Beauty ofEventlet
Here’s a nice little article about using node.js to implement a port forwarder. The two Python examples he cited were butt-ugly (actually, he linked to one butt-ugly example twice accidentally). Surely we can make Python look better!
from eventlet.green import socket import eventlet def callback(): print "called back" def forward(source, dest, cb = lambda: None): while True: d = source.recv(1024) if d == '': cb() break dest.sendall(d) listener = socket.socket() listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1) listener.bind(('localhost', 7000)) listener.listen(500) while True: client, addr = listener.accept() server = socket.create_connection(('localhost', 22)) eventlet.spawn_n(forward, client, server, callback) eventlet.spawn_n(forward, server, client)
To me that seems a little bit more readable than the node.js version, and it’s a little bit shorter, as well. I’m particularly happy about how the forward function is used bidirectionally, so there’s no duplication of that logic. Thanks to Eventlet, it’s just as scalable as node.js; you could connect thousands of clients to this thing.