码迷,mamicode.com
首页 > 编程语言 > 详细

python网络编程(基于twisted的客户端编程)

时间:2016-01-12 21:36:47      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱: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.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()



python网络编程(基于twisted的客户端编程)

标签:

原文地址:http://blog.csdn.net/feixiaoxing/article/details/50506342

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!