码迷,mamicode.com
首页 > 其他好文 > 详细

协同程序例子(multitask)

时间:2016-01-20 15:59:21      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:multitask   python   协同程序   

#!/usr/bin/python
#coding:utf-8

from __future__ import with_statement
from contextlib import closing
import socket
import multitask

def client_handler(sock):
    with closing(sock):
        while True:
            data=(yield multitask.recv(sock,1024))
            if not data:
                break
            yield multitask.send(sock,data)

def echo_server(hostname,port):
    addrinfo=socket.getaddrinfo(hostname,port,socket.AF_UNSPEC,socket.SOCK_STREAM)
    (family,socktype,proto,canonname,sockaddr)=addrinfo[0]
    with closing(socket.socket(family,socktype,proto)) as sock:
        sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        sock.bind(sockaddr)
        sock.listen(5)
        while True:
            multitask.add(client_handler((yield multitask.accept(sock))[0]))
            
if __name__==‘__main__‘:
    import sys
    hostname=None
    port=1111
    if len(sys.argv)>1:
        hostname=sys.argv[1]
    if len(sys.argv)>2:
        port=int(sys.argv[2])
    multitask.add(echo_server(hostname,port))
    try:
        multitask.run()
    except KeyboardInterrupt:
        pass

书上抄的,以后对代码再做解释,目前还看不懂

协同程序例子(multitask)

标签:multitask   python   协同程序   

原文地址:http://zhoubin50.blog.51cto.com/5233664/1736670

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!