一、简介
twisted是一个封装好的网络通信的库,可以帮助我们快速进行网络编程。注意,python3中,字符串必须转码成utf8的格式,否则无法发送。比如str("test").encode("utf8")
即可
二、服务端
服务器需要进行如下操作:
1、在某个端口上一直监听客户端的请求
2、接收到客户端请求后,向客户端发出相应的回应
主要分为下面几个步骤:
1、继承protocol.Protocol建立有关的协议,并实现有关的回调函数
2、继承protocol.Factory建立通信工厂,并在buildProtocol函数中实例化1中的协议
3、reactor.listenTCP(8000, QuoteFactory()) 在某个端口运行通信工厂
# -*- coding utf-8 -*-
from twisted.internet.protocol import Factory, connectionDone
from twisted.internet import reactor, protocol
class QuoteProtocol(protocol.Protocol):
def __init__(self, factory):
self.factory = factory
def connectionMade(self): # 建立连接后的回调函数
self.factory.numConnections += 1
def dataReceived(self, data): # 接收到数据后的回调函数
print("Number of active connections: %d"
% self.factory.numConnections)
print("Received:%s\n Sending: %s" % (data, self.getQuote()))
self.transport.write(self.getQuote())
self.updateQuote(data)
def connectionLost(self, reason=connectionDone): # 断开连接后的反应
self.factory.numConnections -= 1
def getQuote(self):
return self.factory.quote
def updateQuote(self, quote):
self.factory.quote = quote
class QuoteFactory(Factory):
numConnections = 0
def __init__(self, quote=None): # 数据接收后放在在quote中
self.quote = quote or str("Test").encode("utf8")
def buildProtocol(self, addr):
return QuoteProtocol(self)
reactor.listenTCP(8000, QuoteFactory())
reactor.run()
# service_identity
三、客户端
客户端的作用如下:
1、确定服务器的IP和对应的端口号。
2、向服务器发送有关的数据包
主要分为以下几个步骤:
1、继承protocol.Protocol建立有关的协议,并实现有关的回调函数
2、继承protocol.ClientFactory类,建立客户端通信工厂
3、在通信工厂中实现buildProtocol的协议,并实现链接失败的处理函数
# -*- coding utf-8 -*-
from twisted.internet import reactor, protocol
class QuoteProtocol(protocol.Protocol):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
self.sendQuote()
def sendQuote(self):
self.transport.write(self.factory.quote)
def dataReceived(self, data):
print("Received quote", data)
self.transport.loseConnection()
class QuoteClientFactory(protocol.ClientFactory):
def __init__(self, quote): # quote是需要发送的数据
self.quote = quote
def buildProtocol(self, addr):
return QuoteProtocol(self)
def clientConnectionFailed(self, connector, reason):
print("connection failed", reason.getErrorMessage())
maybeStopReactor()
def clientConnectionLost(self, connector, reason):
print("connection lost", reason.getErrorMessage())
maybeStopReactor()
def maybeStopReactor():
global quote_counter
quote_counter -= 1
if not quote_counter:
reactor.stop()
quotes = [
str("You snooze you lose").encode(),
str("The early brid gets worm").encode(),
str("Carpe diem").encode()]
quote_counter = len(quotes)
for quote in quotes:
reactor.connectTCP('localhost', 8000, QuoteClientFactory(quote))
reactor.run()