python twisted 框架 client 和server 模型

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值