最近一直在学习python 异步库,自编自写了一些个文件,使用代码分享给大家吧
所用知识点
1.asyncio库
2.协程通讯
3.aiofiles库
###### 接收器
import socket
import threading
import time
def run(s,ad):
print("开启线程接收{}的data".format(ad))
da="q"
i=0
data=""
while 1:
if da:
# print("******************{}***************".format(ad))
da=s.recv(1024).decode()
data+=da
else:
i+=1
if i == 20:
break
print("{}的data已完全接收,开始写入".format(ad))
f=open(str(time.time()),"w")
f.write(data)
f.close()
print("{}的data写入结束".format(ad))
l=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
l.bind(("127.0.0.1",12346))
l.listen(5)
while 1:
s,ad=l.accept()
run1 = threading.Thread(target=run, args=(s,ad))
run1.start()
代码实现部分:同路径下要有两个文件
#### 发送器
import asyncio
import socket
import aiofiles
async def readf(queue,filename):
async with aiofiles.open(filename,"r",encoding="utf-8") as asf:
da=await asf.read()
await queue.put(da)
async def sendf(queue):
loop = asyncio.get_running_loop()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(False)
await loop.sock_connect(s, ("127.0.0.1", 12346))
data=await queue.get()
await loop.sock_sendall(s,data.encode())
async def main():
queue1=asyncio.Queue()
queue2=asyncio.Queue()
task=[
asyncio.create_task(sendf(queue1)),
asyncio.create_task(readf(queue1,"test2.txt")),
asyncio.create_task(sendf(queue2)),
asyncio.create_task(readf(queue2,"test3.txt"))
]
await asyncio.gather(*task)
asyncio.run(main())
创建了asyncio.queue
队列实现协程通讯。
参考文章:
https://blog.csdn.net/qq_43402663/article/details/112306070
https://stackoom.com/question/3tasE/%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BD%BF%E7%94%A8Python%E5%BC%82%E6%AD%A5%E4%BB%8E%E6%96%87%E4%BB%B6%E8%AF%BB%E5%8F%96%E5%92%8C%E8%B0%83%E7%94%A8API%E6%AF%94%E5%90%8C%E6%AD%A5%E6%85%A2
https://blog.csdn.net/sunt2018/article/details/107716615
https://blog.csdn.net/meiyisi20901/article/details/100987914