您的位置:首页 > 其它

A simple echo client & server based on twisted framework

2013-07-31 15:59 651 查看
echoserver.py

from twisted.internet.protocol import Protocol, ServerFactory
from twisted.internet import reactor

__author__ = 'xueleng'

class Echo(Protocol):
def dataReceived(self, data):
self.transport.write(data)

class EchoFactory(ServerFactory):
def buildProtocol(self, addr):
return Echo();

reactor.listenTCP(8000, EchoFactory())
reactor.run()


echoclient.py

from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor

__author__ = 'xueleng'

class EchoClient(Protocol):
def connectionMade(self):
self.transport.write('Hello, World!')

def dataReceived(self, data):
print 'Server said: %s' % data
self.transport.loseConnection()

class EchoFactory(ClientFactory):
def buildProtocol(self, addr):
return EchoClient()

def clientConnectionFailed(self, connector, reason):
print 'Connection failed'
reactor.stop()

def clientConnectionLost(self, connector, reason):
print 'Connection lose'
reactor.stop()

reactor.connectTCP('localhost', 8000, EchoFactory())
reactor.run()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: