zoukankan      html  css  js  c++  java
  • python-twisted

    环境:win7 64位,python 2.7.3

    安装: 

    http://twistedmatrix.com/Releases/Twisted/14.0/Twisted-14.0.0.win-amd64-py2.7.exe

    https://pypi.python.org/packages/2.7/z/zope.interface/zope.interface-4.1.1.win-amd64-py2.7.exe#md5=c3e22b49f84adaf169ec0d52eded4c8d

    视需要安装:http://softlayer-sng.dl.sourceforge.net/project/wxpython/wxPython/3.0.0.0/wxPython3.0-win64-3.0.0.0-py27.exe

    helloworld:

    simpleserv.py(服务器端):

    from twisted.internet import reactor, protocol
    
    
    class Echo(protocol.Protocol):
        """This is just about the simplest possible protocol"""
        
        def dataReceived(self, data):
            "As soon as any data is received, write it back."
            self.transport.write(data)
    
    
    def main():
        """This runs the protocol on port 8000"""
        factory = protocol.ServerFactory()
        factory.protocol = Echo
        reactor.listenTCP(8000,factory)
        reactor.run()
    
    # this only runs if the module was *not* imported
    if __name__ == '__main__':
        main()
    

      simpleclient.py(客户端)

    from twisted.internet import reactor, protocol
    
    
    # a client protocol
    
    class EchoClient(protocol.Protocol):
        """Once connected, send a message, then print the result."""
        
        def connectionMade(self):
            self.transport.write("hello, world!")
        
        def dataReceived(self, data):
            "As soon as any data is received, write it back."
            print "Server said:", data
            data2= raw_input()
            if data2!='EOM':
                self.transport.write(data2)
            else:        
                self.transport.loseConnection()
        
        def connectionLost(self, reason):
            print "connection lost"
    
    class EchoFactory(protocol.ClientFactory):
        protocol = EchoClient
    
        def clientConnectionFailed(self, connector, reason):
            print "Connection failed - goodbye!"
            reactor.stop()
        
        def clientConnectionLost(self, connector, reason):
            print "Connection lost - goodbye!"
            reactor.stop()
    
    
    # this connects the protocol to a server runing on port 8000
    def main():
        f = EchoFactory()
        reactor.connectTCP("localhost", 8000, f)
        reactor.run()
    
    # this only runs if the module was *not* imported
    if __name__ == '__main__':
        main()
    

      

    测试:

    1.开启服务器端

    2.开启客户端:

    更多文档参考这里

  • 相关阅读:
    linux文件IO操作篇 (二) 缓冲文件
    信号量和互斥锁的区别
    linux 无锁化编程
    C语言中 time相关的函数 头文件
    printf 打印字体和背景带颜色的输出的方法
    在win10环境下安装Cygwin,可以GCC编译
    学习《大话存储》
    linux内核态和用户态的信号量
    学习Makefile
    git 环境搭建
  • 原文地址:https://www.cnblogs.com/Tommy-Yu/p/3940658.html
Copyright © 2011-2022 走看看