检测为什么关闭套接字:FIN vs RST

时间:2018-11-16 20:56:33

标签: python python-3.x sockets tcp python-asyncio

是否可以检测为什么在Python中关闭了套接字,即对方发送了FIN还是RST?

我知道检测另一端是否已发送FIN或RST的唯一方法是从套接字读取,并且如果获得空(字节)字符串,则我们已收到FIN或RST。但是如何知道哪一个呢?

import asyncio
import socket

async def async_main(loop):

    server_sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM,
                                proto=socket.IPPROTO_TCP)
    server_sock.setblocking(False)
    server_sock.bind(('', 8080))
    server_sock.listen(socket.IPPROTO_TCP)

    loop = asyncio.get_event_loop()
    sock, adddress = await loop.sock_accept(server_sock)

    while True:
        data = await loop.sock_recv(sock, 1024)
        if data == b'':
            # Socket closed, but how?
            break
        print(data)

loop = asyncio.get_event_loop()
loop.run_until_complete(async_main(loop))

1 个答案:

答案 0 :(得分:2)

基于詹姆斯·K·波尔克(James K Polk)的comment(我认为是正确的),您可以通过捕获适当的异常来区分FINRST

    while True:
        is_rst = False
        try:
            data = await loop.sock_recv(sock, 1024)
        except IOError as e:
            if e.errno == errno.ECONNRESET:
                data = b''
                is_rst = True
            else:
               raise
        if data == b'':
            # Connection closed - use is_rst to distinguish
            # between RST and FIN
            break
        print(data)