简体   繁体   English

WinSock:从套接字删除数据

[英]WinSock: Remove data from socket

I want to receive data from a socket without specifing a buffer. 我想从套接字接收数据而不指定缓冲区。 So I just want to remove x bytes from the incoming data buffer. 所以我只想从传入的数据缓冲区中删除x字节。

I have the following code (truncated): 我有以下代码(被截断):

recv(gSocket, NULL, userDataLength, 0);

But when I execute the code above the return value of recv() is SOCKET_ERROR and WSAGetLastError() returns WSAECONNABORTED . 但是当我执行上面的代码时, recv()的返回值是SOCKET_ERRORWSAGetLastError()返回WSAECONNABORTED Furthermore my connection get's closed. 此外,我的连接已关闭。

Question: Is it not possible, to use the receive function for removing data from the RX buffer of the socket? 问题:不能使用接收功能从套接字的RX缓冲区中删除数据吗?

I want to receive data from a socket without specifing a buffer. 我想从套接字接收数据而不指定缓冲区。

Sorry, but that is simply not possible. 抱歉,但这根本不可能。 You must provide a buffer to receive the bytes. 您必须提供一个缓冲区以接收字节。 If you don't want to use the bytes, simply discard the buffer after you have read into it. 如果不想使用字节,只需在读入缓冲区后就丢弃它。

I just want to remove x bytes from the incoming data buffer. 我只想从传入的数据缓冲区中删除x字节。

There is no API for that. 没有API。 You must read the bytes into a valid buffer. 您必须将字节读入有效缓冲区。 What you do with that buffer afterwards is up to you. 之后,您将对该缓冲区执行的操作由您决定。

when I execute the code above the return value of recv() is SOCKET_ERROR and WSAGetLastError() returns WSAECONNABORTED . 当我执行以上代码时, recv()的返回值为SOCKET_ERRORWSAGetLastError()返回WSAECONNABORTED

I would have expected WSAEFAULT instead. 我本来希望WSAEFAULT

Is it not possible, to use the receive function for removing data from the RX buffer of the socket? 无法使用接收功能从套接字的RX缓冲区中删除数据吗?

Sure, it is possible. 当然可以。 You simply have to read the bytes into a buffer, even if it is just a temporary buffer, eg: 您只需将字节读取到缓冲区中,即使它只是一个临时缓冲区,例如:

int ignoreBytes(SOCKET sock, int numBytes)
{
    u_char buf[256];
    while (numBytes > 0)
    {
        int numRead = recv(sock, (char*)buf, min(sizeof(buf), numBytes), 0);
        if (numRead <= 0)
            return numRead;
        numBytes -= numRead;
    }
    return 1;
}

ignoreBytes(gSocket, userDataLength);

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

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