1. twisted簡介:
twisted是一個網絡開發架構,可以開發完整的異步網絡應用程式和協定,因為twisted提供了網絡協定,線程,安全性和身份驗證,IM,DBMS資料庫內建,WEB,EMAIL,GUI內建開發工具...等一系列元件提供給開發這使用,它是一個完整的事件驅動的網絡架構。
2.twisted的特點:
從twisted簡介中可以看出,twisted具有以下特點:
.作為架構,支援各種網絡協定,例如:TCP/IP,UDP,SSL/TLS、HTTP、IMAP、SSH、IRC以及FTP;
.提供了GUI內建開發工具,同時,也提供了各種協定的服務端和用戶端的實作;
.基于事件驅動,事件是twisted運轉的核心,是發生各種動作的啟動器;
.跨平台,twisted是一個跨平台的網絡應用程式開發架構。
3.twisted的安裝:
由于twisted不是python标準庫,是以需要手動安裝,用pip install twisted指令進行安裝,方法如下:
pip install twisted
#如果提示“ERROR:...Consider using the `--user` option or check the permissions.”,則加上 --user參數,如下:
pip install twisted --user
也可以參考如下連結:
python3可視化-pyecharts的安裝出錯,“ERROR: Could not install packages due to an EnvironmentError: [Errno 13]“_liranke的專欄-CSDN部落格利用pyecharts可以制作可視化圖形。網址:https://github.com/pyecharts/pyecharts。安裝出錯:Installing collected packages: MarkupSafe, jinja2, wcwidth, prettytable, simplejson, pyechartsERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied
https://blog.csdn.net/liranke/article/details/119817780
3.twisted案例:一個簡單的TCP連結的實作,包括服務端和用戶端
程式功能:用戶端發消息給服務端,服務端将收到消息的時間和收到的消息一起發送給用戶端。
程式清單:
server端代碼(wisted_server.py):
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor
# from twisted.python.compat import raw_input
IP_HOST = "127.0.0.1"
IP_PORT = 7777
class MyClientProtocol(Protocol):
def sendData(self):
data = input("> ") # raw_input
if data:
print("send: %s" % data)
self.transport.write(str.encode(data))
else:
self.transport.loseConnection()
def connectionMade(self):
print("connectionMade of client")
self.sendData()
def dataReceived(self, data):
print("recv:" + data.decode())
self.sendData()
class MyClientFactory(ClientFactory):
protocol = MyClientProtocol
clientConnectionLost = clientConnectionFailed = \
lambda self, connector, reason: reactor.stop()
# main function
if __name__ == '__main__':
print("======twisted client main begin======")
print("connect server...")
reactor.connectTCP(IP_HOST, IP_PORT, MyClientFactory())
reactor.run()
client端代碼(twisted_client.py):
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
from time import ctime
IP_PORT = 7777
clients = []
class MyServerProtocol(Protocol):
def connectionMade(self):
clnt = self.clnt = self.transport.getPeer().host
print("connected from:" + clnt)
# self.factory.numProtocols = self.factory.numProtocols + 1
# self.transport.write(
# "歡迎來到Spread Site, 你是第%s個用戶端使用者!\n" % (self.factory.numProtocols)
# )
# print
# "new connect: %d" % (self.factory.numProtocols)
# clients.append(self)
def connectionLost(self, reason):
print("lost connection")
# self.factory.numProtocols = self.factory.numProtocols - 1
# clients.remove(self)
# print("lost connect: %d" % (self.factory.numProtocols))
def dataReceived(self, data):
data_str = data.decode()
print("dataReceived:" + data_str)
if data_str == "quit":
self.transport.loseConnection()
else:
send_str = '[%s] %s' % (ctime(), data_str)
send_bytes = str.encode(send_str)
#print("data send:" + data_str)
self.transport.write(send_bytes)
#main function
if __name__ == '__main__':
print("======twisted server main begin======")
factory = Factory()
factory.protocol = MyServerProtocol
print("listent...")
reactor.listenTCP(IP_PORT, factory)
reactor.run()
運作結果:
server端運作結果:
python twisted_server.py
======twisted server main begin======
listent...
connected from:127.0.0.1
dataReceived:12345
dataReceived:qwert
dataReceived:quit
lost connection
client端運作結果:
python twisted_client.py
======twisted client main begin======
connect server...
connectionMade of client
> 12345
send: 12345
recv:[Wed Sep 29 08:59:48 2021] 12345
> qwert
send: qwert
recv:[Wed Sep 29 08:59:50 2021] qwert
> quit
send: quit
Process finished with exit code 0
利用成熟的架構,不必重建立輪子。