使用Twisted替换asyncore进行socket编程

用了一年多asyncore  发现太不好控制了~~  决定换 Twisted来做  异步socket 的框架

下面是 根据官方例子改变的 发送http请求的 代码~~

from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from zope.interface import implements
from twisted.internet.defer import succeed
from twisted.web.iweb import IBodyProducer
from twisted.internet.protocol import ClientCreator

class StringProducer(object):
    implements(IBodyProducer)

    def __init__(self, body):
        self.body = body
        self.length = len(body)

    def startProducing(self, consumer):
        consumer.write(self.body)
        return succeed(None)

    def pauseProducing(self):
        pass

    def stopProducing(self):
        pass

class BeginningPrinter(Protocol):

    def __init__(self, finished, results):
        self.finished = finished
        self.remaining = 1024 * 100
        self.results = results

    def dataReceived(self, bytes):
        if self.remaining:
            display = bytes[:self.remaining]
            self.results.append(display)
            self.remaining -= len(display)

    def connectionLost(self, reason):
        self.finished.callback(None)

    def connectionFailed(self, reason):
        print 'Connection failed. Reason:', reason

import simplejson as json
import operator ,uuid,logging
from xml.dom.minidom import parseString

def refresh_url(addresses,command):
    from twisted.internet import reactor
    errors = []
    results = []

    def cbRequest(response,address):
        finished = Deferred()
        response.deliverBody(BeginningPrinter(finished,results))
        return finished

    def cbShutdown(ignored):
        if len(counter)+len(errors) == len(addresses):
            reactor.stop()

    def cbError(err,address):
        errors.append({address:err.getErrorMessage()})

    agent = Agent(reactor, connectTimeout=4)
    for address in addresses:
        client = agent.request(
            'POST',
            'http://%s:%d' % (address.strip(),21108),
            Headers(),
            StringProducer(command))
        client.addCallback(cbRequest,address).addErrback(cbError,address)
        client.addBoth(cbShutdown)
    reactor.run()
    return  results,errors

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值