Twisted是用Python寫的事件驅動的網絡引擎,開源MIT協議,目前Twisted主要運行於Python2上,越來越多的子集將支持Python3.
Twisted支持許多通用的網絡協議,如SMTP、POP3、IMAP、SSHV2和DNS等。
一、Twisted的安裝
在cmd下直接運行pipinstall Twisted,需要管理員權限。
二、服務器代碼編寫
1、需要引用的庫
from twisted.internet
import protocol, reactor
from twisted.internet.endpoints
import TCP4ServerEndpoint
# TCP4ServerEndpoint 需要win32api
from time import ctime
2、定義服務器端協議類
class TSServerProtocol(protocol.Protocol):
"""
服務器端協議
每一個客戶端連接對應一個實例。
"""
def __init__(self):
self.clientInfo =
"" # clientInfo 將保存客戶端連接信息。
def connectionMade(self):
self.clientInfo =
self.transport.getPeer()
print("來自%s的連接" % (self.clientInfo))
def dataReceived(self,
data):
recData = data.decode()
print("收到來自%s的數據:%s" % (self.clientInfo, recData))
rep = '[%s] %s' % (ctime(), recData)
self.transport.write(rep.encode())
3、定義服務器端工廠類
class TSServerFactory(protocol.Factory):
def buildProtocol(self,
addr):
return TSServerProtocol()
4、使用reactor啓動端口監聽
endpoint = TCP4ServerEndpoint(reactor, PORT)
endpoint.listen(TSServerFactory())
print("等待客戶端連接")
reactor.run()
三、客戶端代碼的編寫
1、引用的庫
from twisted.internet
import protocol, reactor
2、定義客戶端協議類
class TSClientProtocol(protocol.Protocol):
def sendData(self):
data = input("> ")
if data:
self.transport.write(data.encode())
else:
self.transport.loseConnection()
def connectionMade(self):
self.sendData()
def dataReceived(self,
data):
recData = data.decode() # 將二進制數據轉換爲字符串數據。
print("從服務器上收到的數據:%s" % (recData))
self.sendData()
3、定義客戶端工廠類
class TSClientFactory(protocol.ClientFactory):
protocol = TSClientProtocol
clientConnectionLost = clientConnectionFailed =
lambda self,
connector, reason:reactor.stop()
4、使用reactor啓動連接
reactor.connectTCP(HOST, PORT, TSClientFactory())
reactor.run()
備註:
有些功能需要win32api模塊,可從從https://sourceforge.net/projects/pywin32下載對應的版本