当peer在winsock 2中重置TCP连接时,如何避免数据丢失?

时间:2012-03-18 03:34:29

标签: tcp router upnp winsock2

我正在编写一个UPnP客户端,我的一个测试路由器总是“猛烈”关闭连接,而不是在发送响应后进行正常的shutdown-send。这导致我的recv调用无法获取数据。

我知道数据存在,因为我可以在数据包嗅探器中看到它。

如果我的代码快速前进到足以在连接重置之前重新获取数据,那么我将获得数据。在许多情况下,对等体在重新连接之前重置连接,导致没有数据复制到我的接收缓冲区,并且来自recv的WSAECONNRESET错误。

任何想法如何解决我的问题以容忍netgear路由器中写得不好的UPnP实现?

我尝试使用WSAEventSelect并使读取异步,这似乎有所帮助,但它并不总是有效。

// Object that manages reliably sending and receiving, even if the
// peer does stupid things like slamming connection shut at EOF
class Transceiver
{
    SOCKET sock;
    AutoWSACloseEvent syncEvent;

    // Buffer pool
    template<size_t bufferSize>
    struct Buffer
        : public SLIST_ENTRY
        , public AutoPool<Buffer<bufferSize>, false>
    {
        char data[bufferSize];

        size_t size() const
        {
            return bufferSize;
        }
    };

public:
    Transceiver() : sock(INVALID_SOCKET)
    {
    }
    int Init(SOCKET sock);
    int SendAll(const std::string &data);
    int ReceiveAll(std::string &data);
};



int UpnpNat::Transceiver::Init(SOCKET sock)
{
    int err;

    this->sock = sock;
    syncEvent = WSACreateEvent();
    if (!syncEvent)
        return ErrorHook(WSAGetLastError());
    err = WSAEventSelect(sock, syncEvent, FD_READ | FD_CLOSE);
    if (err == SOCKET_ERROR)
        return ErrorHook(WSAGetLastError());

    return NO_ERROR;
}

int UpnpNat::Transceiver::SendAll(const std::string &request)
{
    for (int ofs = 0; ofs < (int)request.length(); )
    {
        auto xferSize = send(sock, &request[ofs], (int)request.length() - ofs, 0);
        if (xferSize == SOCKET_ERROR)
            return ErrorHook(WSAGetLastError());
        ofs += xferSize;
    }

    return NO_ERROR;
}

int UpnpNat::Transceiver::ReceiveAll(std::string &response)
{
    int err = NO_ERROR;
    int xferSize;

    auto responseBuf = MakeAutoDelete(new Buffer<16384>());
    if (!responseBuf)
        return ErrorHook(ERROR_OUTOFMEMORY);

    bool needRecvWait = false;

    for (;;)
    {
        if (needRecvWait)
        {
            needRecvWait = false;
            if (WSAWaitForMultipleEvents(1, syncEvent.Storage(),
                    FALSE, 30000, FALSE) != WAIT_OBJECT_0)
            {
                err = WSAETIMEDOUT;
                return ErrorHook(err);
            }

            WSANETWORKEVENTS wsane;
            ZeroInit(&wsane);
            err = WSAEnumNetworkEvents(sock, syncEvent, &wsane);
            if (err == SOCKET_ERROR)
                return ErrorHook(WSAGetLastError());

            if (wsane.lNetworkEvents & FD_CLOSE)
            {
                err = wsane.iErrorCode[FD_CLOSE_BIT];
                break;
            }

            if ((wsane.lNetworkEvents & FD_READ) == 0)
            {
                continue;
            }

            if (wsane.iErrorCode[FD_READ_BIT] != NO_ERROR)
                return ErrorHook(wsane.iErrorCode[FD_READ_BIT]);
        }

        xferSize = recv(sock, responseBuf->data, (int)responseBuf->size(), 
                MSG_PARTIAL);
        if (xferSize == SOCKET_ERROR)
        {
            err = WSAGetLastError();
            if (err == WSAEWOULDBLOCK)
            {
                needRecvWait = true;
                continue;
            }
            // Workaround for crap routers that slam connection shut at EOF
            if (err == WSAECONNRESET && response.length() > 0)
                return NO_ERROR;

            return ErrorHook(WSAGetLastError());
        }
        if (xferSize <= 0)
            break;

        response.append(responseBuf->data, 0, (std::string::size_type)xferSize);
    }

    return ErrorHook(err);
}

1 个答案:

答案 0 :(得分:2)

如果通过'猛击'你的意思是'发送一个RST',那么你无能为力。如果收到RST,TCP堆栈必须中止连接并丢弃所有未决数据。