The Beauty of Eventlet

The Beauty of Eventlet,第1张

The Beauty of Eventlet « Eventlet

The Beauty of Eventlet

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.

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/2089226.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-07-22
下一篇 2022-07-22

发表评论

登录后才能评论

评论列表(0条)

保存