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.开启客户端:
更多文档参考这里。