Python使用asyncio流打开连接、发送和接收多个传输,然后优雅地关闭连接的正确方法

2024-09-27 09:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问的是,相对于使用asyncio客户端流发送数据和接收来自服务器的响应,我的进程或代码哪里不正确。当我调用断开客户端连接的方法时,会引发异常。我正在学习python asyncio,并在尝试关闭客户端连接的测试过程中遇到异常。我正在努力。创建到服务器的客户端连接(2)。保持客户端连接打开,以便可以跨多个发送/接收周期使用它(3)。完成后,优雅地关闭客户端连接

这是包含用于创建流编写器的asyncio方法的类

  class hl7_client_sender:
      SB = b'\x1B'
      EB = b'\x1C'
      CR = b'\x0D'

      def __init__(self,address,port,timeout=-1,retry=3.0):
          self._resend=0
          self._timeout= timeout
          self._retry = retry
          #self._reader, self._writer = await asyncio.open_connection(address,port)
          self._address = address
          self._port = port
          self._writer = None
          self._reader = None

async def connect(self):
    self._reader, self._writer = await asyncio.open_connection(self._address,self._port)

async def disconnect(self):
    await self._writer.wait_closed()

这是我的驱动程序中的代码,在调用断开连接时发生异常

  #test send and respond
  import asyncio
  import string
  import unicodedata
  import simple_hl7_client
  import time
  ##open a connectino sleep 5 seconds then close###
  myclient = simple_hl7_client.hl7_client_sender('192.168.226.128',54321)
  asyncio.run(myclient.connect())
  time.sleep(3)
  asyncio.run(myclient.disconnect())

调用asycnio.run(myclient.disconnect()时发生异常

这是一个例外:

      Traceback (most recent call last):
        File ".\test_simple_hl7_client.py", line 11, in <module>
   asyncio.run(myclient.disconnect())
   File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\runners.py",           line 43, in run
      return loop.run_until_complete(main)
    File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 583, in run_until_complete
      return future.result()
    File "D:\data\FromOldPC\code\ASYNCIOTESTING\simple_hl7_client.py", line 23, in disconnect
      self._writer.close()
    File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\streams.py", line 317, in close
      return self._transport.close()
    File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 663, in close
      self._loop.call_soon(self._call_connection_lost, None)
    File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 687, in call_soon
      self._check_closed()
    File "C:\Users\billg\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 479, in _check_closed
      raise RuntimeError('Event loop is closed')
  RuntimeError: Event loop is closed

Tags: runinpyselfclientasyncio客户端local

热门问题