首页 > 解决方案 > 实现Asyncio通过socket同时发送多个文件

问题描述

刚开始使用 asyncio 不确定我有多接近每次运行此功能时,如果它仍在发送,我不想打扰以前的文件循环发送,因此最终我可以使用相同的文件同时发送无限数量的文件功能

 async def fileread(self):


    loop = asyncio.get_event_loop()
    executor = ThreadPoolExecutor(8)

    tasks = [loop.run_in_executor(executor,self.fileread())]
    #tasks.append(self.fileread())


    global flsize



    progress = tqdm.tqdm(range(flsize), f"Sending {fp}", unit="B", unit_scale=True,
                        unit_divisor=1024)


    with open(fp, "rb") as f:


      bytes_read = f.read(flsize)  # NEED TO SEND SMALL BYTS

      bytes_read_small = f.read(4096)



      while not flsize == 0: 



                     if not bytes_read:
                         # file transmitting is done
                         break

                     global file_sent
                     file_sent = 1

                     self.s.sendall(bytes_read)  #loop.sendall

                     progress.update(len(bytes_read))

                     file_sent = 1  

                     self.s.shutdown()

                     self.s.close()

      await asyncio.wait(tasks)


 def connect_to_server(self, *args, **kwargs):

             try:  

                    loop = asyncio.new_event_loop()
                    loop.run_until_complete(self.fileread())
                    #asyncio.run(self.fileread())

                    # loop.close() #not sure

            except:

                    print("no op")

标签: pythonsocketspython-asyncio

解决方案


推荐阅读