简体   繁体   English

如何正确关闭使用 local_addr 的异步连接

[英]How to properly close an asyncio connection where local_addr is used

I am making a TCP connection using asyncio and then closing it some time later.我正在使用 asyncio 建立 TCP 连接,然后在一段时间后关闭它。 I need to specify local_addr as there are a number of interfaces available on the host machine.我需要指定local_addr因为主机上有许多可用的接口。

import asyncio

async def main():
    print("Connecting...")
    try:
        reader, writer = await asyncio.open_connection('169.254.6.123', 55555, local_addr=('169.254.6.11', 15333))
    except Exception as e:
        print(e)
        return
        
    await asyncio.sleep(3)
    writer.close()
    ret = await writer.wait_closed()
    print(ret)
    
    
asyncio.run(main())

This works fine on first run but then on second run I get an error back:这在第一次运行时工作正常,但在第二次运行时我得到一个错误:

[WinError 52] You were not connected because a duplicate name exists on the network. [WinError 52] 您没有连接,因为网络上存在重复的名称。

If I do NOT have the local_addr set then it works fine (I have to disable all my other network interfaces to ensure it gets routed otherwise it times out as the 'network location cannot be reached' - can't find a route).如果我没有设置local_addr那么它就可以正常工作(我必须禁用所有其他网络接口以确保它被路由,否则它会超时,因为“网络位置无法到达” - 找不到路由)。

Am I doing something wrong in closing the connection when local_addr is set?设置local_addr时,我在关闭连接时做错了什么吗?

It works on retry with local_addr set if I wait some time before trying to run again (I guess some cache is cleared??).如果我在尝试再次运行之前等待一段时间(我猜一些缓存被清除了??),它可以使用local_addr设置重试。

Not sure if this is only an issue on Windows (using Windows 10)不确定这是否只是 Windows 上的问题(使用 Windows 10)

I was re-using the port...so OS was giving the error.我正在重新使用端口......所以操作系统给出了错误。

Set local_addr port to 0 and the OS will choose the port.local_addr端口设置为 0,操作系统将选择该端口。 See this answer .看到这个答案

reader, writer = await asyncio.open_connection('169.254.6.123', 55555, local_addr=('169.254.6.11', 0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM