zoukankan      html  css  js  c++  java
  • python编程(基于twisted的client编程)

    【 声明:版权全部,欢迎转载。请勿用于商业用途。 联系信箱:feixiaoxing @163.com】


        python的twisted比較有意思,既能够做server方面的编程,也能够做client方面的编程。关于这方面的编程。最简单的样例就是echo。


        client 代码例如以下,

    #!/usr/bin/python
    
    from twisted.internet.protocol import Protocol, ClientFactory
    from sys import stdout
    from twisted.internet import reactor
    
    class 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:', reason
    	
    	def clientConnectionFailed(self, connector, reason):
    		print 'Connection failed. Reason:', reason
    
    if __name__ == '__main__':
    	reactor.connectTCP('localhost', 1234, EchoClientFactory())
    	reactor.run()

        server 代码例如以下,

    #!/usr/bin/python
    
    from twisted.internet import protocol, reactor, endpoints
    
    class 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()
    
    


  • 相关阅读:
    独立构件风格之C2风格
    Mysql远程授权报语法错误
    Vuforia3D模型上传
    Hololens Vuforia 物体识别
    C盘无损分区
    MRTK 当进入某个物体时调用的函数
    Java实现斐波那契数列的两种方法
    Leetcode452. 用最少数量的箭引爆气球(排序+贪心)
    Java对二维数组排序
    帮你理清js的继承
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7137426.html
Copyright © 2011-2022 走看看