zoukankan      html  css  js  c++  java
  • python基于协程的网络库gevent、eventlet

    python网络库也有了基于协程的实现,比较著名的是 gevent、eventlet 它两之间的关系可以参照

    Comparing gevent to eventlet, 本文主要简单介绍一下eventlet一个例子

    客户端:

    import eventlet
    from eventlet.green import urllib2

    def myfetch(myurl, i):
    req = urllib2.Request(myurl)
    req.add_header('User-agent', 'Mozilla 5.10')
    res = urllib2.urlopen(req, timeout = 4)
    body = res.read();
    size = len(body);
    print (i, 'body size ' ,size)
    return size


    myurl = "http://127.0.0.1:6000"
    pool = eventlet.GreenPool(1000)
    for i in range(1, 200):
    pool.spawn(myfetch, myurl, i)
    #print i
    pool.waitall()
    print "--finish --GreenPool"
    服务端:

    #! /usr/bin/env python
    """
    Simple server that listens on port 6000 and echos back every input to
    the client. To try out the server, start it up by running this file.
    Connect to it with:
    telnet localhost 6000
    You terminate your connection by terminating telnet (typically Ctrl-]
    and then 'quit')
    """
    from __future__ import print_function

    import eventlet


    def handle(fd): #单个协程的处理逻辑
    print("client connected")
    while True:
    # pass through every non-eof line
    x = fd.readline()
    if not x:
    break
    fd.write(x)
    fd.flush()
    print("echoed", x, end=' ')
    print("client disconnected")

    print("server socket listening on port 6000")
    server = eventlet.listen(('0.0.0.0', 6000)) #监听6000端口
    pool = eventlet.GreenPool() #构造协程池
    while True:
    try:
    new_sock, address = server.accept() #accept新的连接
    print("accepted", address)
    pool.spawn_n(handle, new_sock.makefile('rw')) #将新的连接交由一个新的协程去处理
    except (SystemExit, KeyboardInterrupt):
    break
    上面的例子可以看出eventlet接口还是非常的简洁和优雅的,至于稳定性和成熟度还待真实的场景去验证,
    使用eventlet快速开发一个tcp/http的server还是非常迅速的,因为是基于协程的, 对于网络IO密集型的场景
    速度不会太差.
    eventlet已知的在openstack项目中有使用.
    ---------------------
    作者:mumumuwudi
    来源:CSDN
    原文:https://blog.csdn.net/mumumuwudi/article/details/47116493
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    python调用go
    manjaro安装qt
    Ubuntu16.04 ROS安装kinect2并获取骨骼数据+配置kinect2_tracker_pd很不专业的博客-程序员宅基地
    Kinect XBOX 360和六轴机械臂的实时映射
    KinectV2.0 VS2019配置记录
    (29条消息) windows下用kinect V2 识别人体骨骼_interstellar-ai的博客-CSDN博客
    Baxter实战:Ubuntu16.04+Kinect2实现动作跟随
    Kinect2和六轴机械臂的实时映射(初步)
    CS395-T: Robot Learning from Demonstration and Interaction
    无需公网IP,远程SSH访问Linux服务器!
  • 原文地址:https://www.cnblogs.com/ExMan/p/10426790.html
Copyright © 2011-2022 走看看