twisted-收发数据

from twisted.internet import stdio, reactor, protocol

from twisted.protocols import basic

import re



class DataForwardingProtocol(protocol.Protocol):

    def __init__(self):

        self.output = None

        self.normalizeNewlines = False



    def dataReceived(self, data):

        if self.normalizeNewlines:

            data = re.sub(r"(\r\n|\n)", "\r\n", data)

        if self.output:

            self.output.write(data)



class StdioProxyProtocol(DataForwardingProtocol):

    def connectionMade(self):

        inputForwarder = DataForwardingProtocol( )

        inputForwarder.output = self.transport

        inputForwarder.normalizeNewlines = True

        stdioWrapper = stdio.StandardIO(inputForwarder)

        self.output = stdioWrapper

        print "Connected to server.  Press ctrl-C to close connection."



class StdioProxyFactory(protocol.ClientFactory):

    protocol = StdioProxyProtocol



    def clientConnectionLost(self, transport, reason):

        reactor.stop( )



    def clientConnectionFailed(self, transport, reason):

        print reason.getErrorMessage( )

        reactor.stop( )



if __name__ == '__main__':

    import sys

    if not len(sys.argv) == 3:

        print "Usage: %s host port" % __file__

        sys.exit(1)



    reactor.connectTCP(sys.argv[1], int(sys.argv[2]), StdioProxyFactory( ))

    reactor.run( )



 

 

 
E:\test>python test.py www.hao123.com 80
Connected to server.  Press ctrl-C to close connection.

 

 

从定义DataForwardingProtocol类开始,每当接收数据时,调用self.output.write将数据传递到self.output(可以是任何对象写入方法)。 DataForwardingProtocolnormalizeNewLines属,如果设置为true,它会将Unix风格的\ N换行符标准化为\ R\ N的更标准的网络协议所使用的换行符。

做为 DataForwardingProtocol的子类, StdioProxyProtocol完成设置工作,一旦连接建立,它就建立一个DataForwardingProtocol的实例,叫inputForwarder,设置它的输出为self.transport,然后包装inputForwarder为twisted.internet.stdio的实例,将inputForwarder挂钩到标准的I / O做为网络连接的替换,从标准输入接收到的数据转发到 StdioProxyProtocol网络连接中,最后,设置StdioProxyProtocol的输出属性为stdioWrapper,因此,从连接接收到的数据将被转发到标准输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值