twisted echo 服务器
由于windows安装twisted十分费尽,这次在centos中练习。
详细解释见注释
from twisted.internet import protocol
from twisted.internet import reactor
# 继承该类
class Echo(protocol.Protocol):
# twisted收到数据就会调用dataReceived方法
def dataReceived(self, data):
# 写此方法,实现功能
# 把受到的数据返回给客户端
self.transport.write(data)
def main():
# 定义基础的工厂类
factory = protocol.ServerFactory()
# 类似socketserver中的handle,所执行的语句均在 handle中。每个链接都会通过echo来生成一个实例。
factory.protocol = Echo
# 类似触发器,监控端口及监视实例。
reactor.listenTCP(1234, factory)
reactor.run()
if __name__ == '__main__':
main()
twisted echo 服务器
from twisted.internet import reactor, protocol
# 定义客户端类,继承protocol protocal
class EchoClient(protocol.Protocol):
# 重写方法,当连接建立,即执行此方法,向transport写
def connectionMade(self):
self.transport.write('Hello, I am chen in client'.encode())
def dataReceived(self, data):
print('Server said:', data)
# 接收到数据即执行此方法,如下口令即关闭此通道。
self.transport.loseConnection()
# 连接中断后执行该方法。
def connectionLost(self, reason):
print('connection lost')
# 工厂类
class EchoFactory(protocol.ClientFactory):
# 类似handle,与之前不同,之前为函数,此处为类
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print('connection failed - goodbye!')
reactor.stop()
def clientConnectionLost(self, connector, reason):
print('connection lost - good bye!')
reactor.stop()
def main():
f = EchoFactory()
reactor.connectTCP('localhost', 1234, f)
reactor.run()
if __name__ == '__main__':
main()