twisted的stdio操作

# 发送与接收
# 通过标准I/O来进行数据发送和接收,将接收到的数据传递到标准输出,并打印数据到标准输出
# 验证:可以通过网络调试助手服务器两边互发数据
#       也可以通过GET / HTTP/1.1\r\nHost: example.webscraping.com\r\nUser-Agent: wswb\r\n\r\n
#       来实现HTTP操作得到网站webscraping返回值

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):

        data = data.decode()
        # print(data)
        if self.normalizeNewLines:
            data = re.sub(r'\r\n|\n', '\r\n', data) # 转换成常见的网络格式\r\n
            # print(data)
        if self.output:
            self.output.write(data.encode())   # 将接受到的数据写入self.output
            # print(self.output)


class StdioProxyProtocol(DataForwardingProtocol):

    def connectionMade(self):
        inputForwarder = DataForwardingProtocol()
        inputForwarder.output = self.transport # 将transport传递给inputForwarder.output
        inputForwarder.normalizeNewLines = True
        # 将实例对象的输出转换传递到为标准I/O输出
        stdioWarpper = stdio.StandardIO(inputForwarder)
        self.output = stdioWarpper
        print('连接到服务器,可以按CTRL+C关闭连接')
        # print(self.output)

class StdioProxyFactory(protocol.ClientFactory):

    protocol=StdioProxyProtocol

    def clientConnectionLost(self, connector, reason):
        # print('1')
        reactor.stop()

    def clientConnectionFailed(self, connector, reason):
        print(reason.getErrorMessage())
        # print('2')
        reactor.stop()

if __name__ == '__main__':
    import sys

    if not len(sys.argv)==3:
        print('格式不对:%s host port' % __file__)
        sys.exit(1)

    reactor.connectTCP(sys.argv[1], int(sys.argv[2]), StdioProxyFactory())
    reactor.run()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值