【 聲明:版權所有,歡迎轉載,請勿用于商業用途。 聯系信箱:feixiaoxing @163.com】
? ? python的twisted比較有意思,既可以做server方面的編程,也可以做client方面的編程。關于這方面的編程,最簡單的例子就是echo。
PYTHON編程?
? ? client 代碼如下,
#!/usr/bin/pythonfrom twisted.internet.protocol import Protocol, ClientFactory
from sys import stdout
from twisted.internet import reactorclass Echo(Protocol):def dataReceived(self, data):stdout.write(data)class EchoClientFactory(ClientFactory):def startedConnecting(self, connector):print 'Started to connect.'def buildProtocol(self, addr):print 'Connected.'return Echo()def clientConnectionLost(self, connector, reason):print 'Lost connection. Reason:', reasondef clientConnectionFailed(self, connector, reason):print 'Connection failed. Reason:', reasonif __name__ == '__main__':reactor.connectTCP('localhost', 1234, EchoClientFactory())reactor.run()
? ? server?代碼如下,
Python編譯?
#!/usr/bin/pythonfrom twisted.internet import protocol, reactor, endpointsclass Echo(protocol.Protocol):def dataReceived(self, data):self.transport.write(data)class EchoFactory(protocol.Factory):def buildProtocol(self, addr):return Echo()if __name__ == '__main__':endpoints.serverFromString(reactor, "tcp:1234").listen(EchoFactory())reactor.run()
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态