http://www.cnblogs.com/sevenyuan/archive/2010/11/22/1884529.html
client:
import twisted
from twisted.internet.selectreactor import SelectReactor
from twisted.internet.protocol import Protocol,ClientFactory,defer
from twisted.internet import stdio,reactor,protocol
from twisted.protocols import basic
import re
import time
class DataForwardingProtocol(protocol.Protocol):
def __init__(self):
self.output=None
self.normalizeNewLines=False
def dataReceived(self,data):
print 'get data: [%s]' % data,'start another write...'
time.sleep(1)
self.transport.write(data)
if self.normalizeNewLines:
pass
# 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
stdioWarpper=stdio.StandardIO(inputForwarder)
self.output=stdioWarpper
print "Connected to server. Press Ctrl-C to close connection."
strsend = "this is kmcfly send a string to baidu.com ,do you know\r\n"
print strsend
self.transport.write(strsend)
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,os
print len(sys.argv)
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()
server:
#! /usr/bin/python
# -*- coding: utf-8 -*-
from twisted.internet import reactor,protocol
from twisted.protocols import basic
class EchoProtocol(basic.LineReceiver):
print 'run EchoProtocol ................here............'
def lineReceived(self,line):
if line=='quit':
self.sendLine("Goodbye.")
self.transport.loseConnection()
else:
print 'get the string :[%s]' % line
self.sendLine(line)
class EchoServerFactory(protocol.ServerFactory):
print 'run EchoServerFactory..........here..............'
protocol=EchoProtocol
if __name__=="__main__":
port=5001
reactor.listenTCP(port,EchoServerFactory())
reactor.run()