异步并发发送文件,边读边发,python

最近一直在学习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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值