twisted TCP服务端:
主要利用protocol.Proctocol和 protocol.ServerFactory
__author__ = 'python'
from twisted.application.service import Application,Service
from twisted.internet import reactor,protocol
class MyProtocol(protocol.Protocol):
def __init__(self,aaa):
self.flag=123
self.aaa=aaa
def dataReceived(self, data):
print data
self.transport.write(self.factory.returnFlag())
def connectionMade(self):
print "connected!"
def connectionLost(self, reason):
print dir(reason)
class MyFactory(protocol.ServerFactory):
def __init__(self):
self.flag="456"
def buildProtocol(self, addr):
p=MyProtocol(999)
p.factory=self
return p
def returnFlag(self):
return self.flag
myfactory=MyFactory()
reactor.listenTCP(8080,myfactory)
reactor.run()
利用telnet测试服务端是否正常:
[root@zkp534 ~]# telnet 192.168.13.187 8080
Trying 192.168.13.187...
Connected to 192.168.13.187.
Escape character is '^]'.
11
45612
456213
456213
456213
456123
456213
456
twisted TCP client:
主要适用protocol.Protocol和protocol.ClientFactory
一个TCP客户端例子如下:
from twisted.internet import reactor,protocol
class QuickDisconnectedProtocol(protocol.Protocol):
def connectionMade(self):
print "connected to %s"%self.transport.getPeer().host
self.transport.loseConnection()
class ClientFactory(protocol.ClientFactory):
protocol=QuickDisconnectedProtocol
def clientConnectionLost(self,connection,reason):
print "lost connection :%s"%reason.getErrorMessage()
reactor.stop()
def clientConnectionFailed(self,connection,reason):
print "connection failed:%s"%reason.getErrorMessage()
reactor.stop()
reactor.connectTCP("10.0.20.150",80,ClientFactory())
reactor.run()