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(可以是任何对象写入方法)。 DataForwardingProtocol 的normalizeNewLines属,如果设置为true,它会将Unix风格的\ N换行符标准化为\ R\ N的更标准的网络协议所使用的换行符。
做为 DataForwardingProtocol的子类, StdioProxyProtocol完成设置工作,一旦连接建立,它就建立一个DataForwardingProtocol的实例,叫inputForwarder,设置它的输出为self.transport,然后包装inputForwarder为twisted.internet.stdio的实例,将inputForwarder挂钩到标准的I / O做为网络连接的替换,从标准输入接收到的数据转发到 StdioProxyProtocol网络连接中,最后,设置StdioProxyProtocol的输出属性为stdioWrapper,因此,从连接接收到的数据将被转发到标准输出。
1004

被折叠的 条评论
为什么被折叠?



