> 文档中心 > Python网络编程(九)-使用twisted框架进行TCP网络链接相关应用的开发,包括server和client

Python网络编程(九)-使用twisted框架进行TCP网络链接相关应用的开发,包括server和client

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 deniedhttps://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, ClientFactoryfrom twisted.internet import reactor# from twisted.python.compat import raw_inputIP_HOST = "127.0.0.1"IP_PORT = 7777class 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 functionif __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, Factoryfrom twisted.internet import reactorfrom time import ctimeIP_PORT = 7777clients = []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 functionif __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


利用成熟的框架,不必重新建轮子。

在线造句网