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.

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。