浙江省高等学校教师教育理论培训

微信搜索“教师资格证岗前培训”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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.

posted on 2012-04-30 07:59  lexus  阅读(267)  评论(0编辑  收藏  举报