S.l.e!ep.¢%

像打了激速一样,以四倍的速度运转,开心的工作
简单、开放、平等的公司文化;尊重个性、自由与个人价值;
posts - 1098, comments - 335, trackbacks - 0, articles - 1
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

WSARecv 函数

Posted on 2009-01-31 04:16 S.l.e!ep.¢% 阅读(5318) 评论(0)  编辑 收藏 引用 所属分类: VC
WSARecv Function

The WSARecv function receives data from a connected socket or a bound connectionless socket.
WSARecv函数从一个socket接收数据

Syntax

int WSARecv(
  __in     SOCKET s,
  __inout  LPWSABUF lpBuffers,
  __in     DWORD dwBufferCount,
  __out    LPDWORD lpNumberOfBytesRecvd,
  __inout  LPDWORD lpFlags,
  __in     LPWSAOVERLAPPED lpOverlapped,
  __in     LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

Parameters

s [in]
A descriptor identifying a connected socket.
一个已经连接的 socket
lpBuffers [in, out]

A pointer to an array of WSABUF structures. Each WSABUF structure contains a pointer to a buffer and the length, in bytes, of the buffer.
一个指向WSABUF结构数组的指针。每一个WSABUF结构包含一个缓冲区的指针和缓冲区的长度。

dwBufferCount
[in]
The number of WSABUF structures in the lpBuffers array.
lpBuffers数组中WSABUF结构的大小。

lpNumberOfBytesRecvd [out]
          A pointer to the number, in bytes, of data received by this call if the receive operation completes immediately. If the lpOverlapped parameter is non-NULL, this parameter is optional and can be set to NULL.
          如果接收操作立即结束,一个指向本调用所接收的字节数的指针。

lpFlags
[in, out]
          A pointer to flags used to modify the behavior of the WSARecv function call. For more information, see the Remarks section.
          一个指向标志位的指针。
 
lpOverlapped [in]
          A pointer to a WSAOVERLAPPED structure (ignored for nonoverlapped sockets).
          一个指向WSAOVERLAPPED结构的指针(对于非重叠套接口则忽略)。      

lpCompletionRoutine
[in]
           A pointer to the completion routine called when the receive operation has been completed (ignored for nonoverlapped sockets).
           一个指向接收操作结束后调用的例程的指针(对于非重叠套接口则忽略)。

Return Value
返回值

If no error occurs and the receive operation has completed immediately, WSARecv returns zero. In this case, the completion routine will have already been scheduled to be called once the calling thread is in the alertable state. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError. The error code WSA_IO_PENDING indicates that the overlapped operation has been successfully initiated and that completion will be indicated at a later time. Any other error code indicates that the overlapped operation was not successfully initiated and no completion indication will occur.

若无错误发生且接收操作立即完成,则WSARecv()函数返回所接收的字节数。如果连接结束,则返回0。请注意在这种情况下完成指示(启动指定的完成例程或设置一个事件对象)将早已发生。否则的话,将返回SOCKET_ERROR错误,应用程序可通过WSAGetLastError()来获取相应的错误代码。错误代码WSA_IO_PENDING表示重叠操作成功启动,过后将有完成指示。任何其他的错误表示重叠操作未能成功地启动,以后也不会有完成指示。

  如果设置了MSG_INTERRUPT标志,则返回值的含义变化。零表示成功,具体含义同上。否则的话,返回值直接包含如下所示的错误代码。由于中断环境中无法调用WSAGetLastError(),故是必需的。请注意仅适用于Win16环境,仅适用于PROTOCOL_INFO结构中设置了XP1_INTERRUPT位的协议。

Error code

Meaning

WSAECONNABORTED

The virtual circuit was terminated due to a time-out or other failure.
由于超时或其他错误导致虚电路中止。

WSAECONNRESET

For a stream socket, the virtual circuit was reset by the remote side. The application should close the socket as it is no longer usable. For a UDP datagram socket, this error would indicate that a previous send operation resulted in an ICMP "Port Unreachable" message.
虚电路被远端复位。

WSAEDISCON

Socket s is message oriented and the virtual circuit was gracefully closed by the remote side.
远端优雅的结束了连接。

WSAEFAULT

The lpBuffers parameter is not completely contained in a valid part of the user address space.

WSAEINPROGRESS

A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
一个阻塞的WinSock调用正在进行中,或者服务提供者仍在处理一个回调函数

WSAEINTR


The (blocking) call was canceled by the WSACancelBlockingCall function.
通过WSACancelBlockingCall()函数取消(阻塞)调用。

WSAEINVAL

The socket has not been bound (for example, with bind).
套接口未用bind()捆绑,或者套接口未用重叠标志创建。

WSAEMSGSIZE

The message was too large to fit into the specified buffer and (for unreliable protocols only) any trailing portion of the message that did not fit into the buffer has been discarded.

WSAENETDOWN


The network subsystem has failed.
网络子系统失效。

WSAENETRESET

For a connection-oriented socket, this error indicates that the connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. For a datagram socket, this error indicates that the time to live has expired.
由于远端的复位造成连接的中止。

WSAENOTCONN


The socket is not connected.
套接口未连接。

WSAENOTSOCK

The descriptor is not a socket.
描述字不是一个套接口。

WSAEOPNOTSUPP

MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only send operations.
设置了MSG_OOB,但是该套接口不是诸如SOCK_STREAM流类型的,与套接口相关的通讯域不支持带外数据,或者套接口是单向的,只支持发送操作。

WSAESHUTDOWN

The socket has been shut down; it is not possible to call WSARecv on a socket after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH.
套接口已经关闭;一个套接口以SD_RECEIVE或 SD_BOTH的how参数shutdown()后,无法进行WSARecv()调用。

WSAETIMEDOUT

The connection has been dropped because of a network failure or because the peer system failed to respond.

WSAEWOULDBLOCK

Windows NT:  
Overlapped sockets: there are too many outstanding overlapped I/O requests. Nonoverlapped sockets: The socket is marked as nonblocking and the receive operation cannot be completed immediately.
重叠套接口:太多重叠的输入/输出请求。非重叠套接口:套接口被标志为非阻塞,但是操作不能立即完成。

WSANOTINITIALISED


A successful WSAStartup call must occur before using this function.
在调用本API之前应成功调用WSAStartup()。

WSA_IO_PENDING

An overlapped operation was successfully initiated and completion will be indicated at a later time.
成功启动一个重叠操作,过后将有完成指示。

WSA_OPERATION_ABORTED

The overlapped operation has been canceled due to the closure of the socket.

Remarks

The WSARecv function provides some additional features compared with the standard recv function in three important areas:

  • It can be used in conjunction with overlapped sockets to perform overlapped recv operations.
  • It allows multiple receive buffers to be specified making it applicable to the scatter/gather type of I/O.
  • The lpFlags parameter is used both on input and returned on output, allowing applications to sense the output state of the MSG_PARTIAL flag bit. However, the MSG_PARTIAL flag bit is not supported by all protocols.

The WSARecv function is used on connected sockets or bound connectionless sockets specified by the s parameter and is used to read incoming data. The socket's local address must be known. For server applications, this is usually done explicitly through bind or implicitly through accept or WSAAccept. Explicit binding is discouraged for client applications. For client applications the socket can become bound implicitly to a local address through connect, WSAConnect, sendto, WSASendTo, or WSAJoinLeaf.

For connected, connectionless sockets, this function restricts the addresses from which received messages are accepted. The function only returns messages from the remote address specified in the connection. Messages from other addresses are (silently) discarded.

For overlapped sockets, WSARecv is used to post one or more buffers into which incoming data will be placed as it becomes available, after which the application-specified completion indication (invocation of the completion routine or setting of an event object) occurs. If the operation does not complete immediately, the final completion status is retrieved through the completion routine or WSAGetOverlappedResult.

Note  All I/O initiated by a given thread is canceled when that thread exits. For overlapped sockets, pending asynchronous operations can fail if the thread is closed before the operations complete. See ExitThread for more information.

If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will be treated as a nonoverlapped socket.

For nonoverlapped sockets, the blocking semantics are identical to that of the standard recv function and the lpOverlapped and lpCompletionRoutine parameters are ignored. Any data that has already been received and buffered by the transport will be copied into the specified user buffers. In the case of a blocking socket with no data currently having been received and buffered by the transport, the call will block until data is received. Windows Sockets 2 does not define any standard blocking time-out mechanism for this function. For protocols acting as byte-stream protocols the stack tries to return as much data as possible subject to the available buffer space and amount of received data available. However, receipt of a single byte is sufficient to unblock the caller. There is no guarantee that more than a single byte will be returned. For protocols acting as message-oriented, a full message is required to unblock the caller.

Note  The socket options SO_RCVTIMEO and SO_SNDTIMEO apply only to blocking sockets.

Whether or not a protocol is acting as byte stream is determined by the setting of XP1_MESSAGE_ORIENTED and XP1_PSEUDO_STREAM in its WSAPROTOCOL_INFO structure and the setting of the MSG_PARTIAL flag passed in to this function (for protocols that support it). The following table lists relevant combinations, (an asterisk (*) indicates that the setting of this bit does not matter in this case).

XP1_MESSAGE_ORIENTED XP1_PSEUDO_STREAM MSG_PARTIAL Acts as
not set * * Byte stream
* Set * Byte stream
set Not set set Byte stream
set Not set not set Message oriented

The buffers are filled in the order in which they appear in the array pointed to by lpBuffers, and the buffers are packed so that no holes are created.

If this function is completed in an overlapped manner, it is the Winsock service provider's responsibility to capture the WSABUF structures before returning from this call. This enables applications to build stack-based WSABUF arrays pointed to by the lpBuffers parameter.

For byte stream-style sockets (for example, type SOCK_STREAM), incoming data is placed into the buffers until the buffers are filled, the connection is closed, or the internally buffered data is exhausted. Regardless of whether or not the incoming data fills all the buffers, the completion indication occurs for overlapped sockets.

For message-oriented sockets (for example, type SOCK_DGRAM), an incoming message is placed into the buffers up to the total size of the buffers, and the completion indication occurs for overlapped sockets. If the message is larger than the buffers, the buffers are filled with the first part of the message. If the MSG_PARTIAL feature is supported by the underlying service provider, the MSG_PARTIAL flag is set in lpFlags and subsequent receive operations will retrieve the rest of the message. If MSG_PARTIAL is not supported but the protocol is reliable, WSARecv generates the error WSAEMSGSIZE and a subsequent receive operation with a larger buffer can be used to retrieve the entire message. Otherwise, (that is, the protocol is unreliable and does not support MSG_PARTIAL), the excess data is lost, and WSARecv generates the error WSAEMSGSIZE.

For connection-oriented sockets, WSARecv can indicate the graceful termination of the virtual circuit in one of two ways that depend on whether the socket is byte stream or message oriented. For byte streams, zero bytes having been read (as indicated by a zero return value to indicate success, and lpNumberOfBytesRecvd value of zero) indicates graceful closure and that no more bytes will ever be read. For message-oriented sockets, where a zero byte message is often allowable, a failure with an error code of WSAEDISCON is used to indicate graceful closure. In any case a return error code of WSAECONNRESET indicates an abortive close has occurred.

The lpFlags parameter can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this function are determined by the socket options and the lpFlags parameter. The latter is constructed by using the bitwise OR operator with any of the values listed in the following table.

Value Meaning
MSG_PEEK Peeks at the incoming data. The data is copied into the buffer, but is not removed from the input queue. This flag is valid only for nonoverlapped sockets.
MSG_OOB Processes OOB data.
MSG_PARTIAL This flag is for message-oriented sockets only. On output, indicates that the data specified is a portion of the message transmitted by the sender. Remaining portions of the message will be specified in subsequent receive operations. A subsequent receive operation with MSG_PARTIAL flag cleared indicates end of sender's message.

As an input parameter, this flag indicates that the receive operation should complete even if only part of a message has been received by the service provider.

MSG_WAITALL The receive request will complete only when one of the following events occurs:

  • The buffer supplied by the caller is completely full.
  • The connection has been closed.
  • The request has been canceled or an error occurred.
Be aware that if the underlying transport does not support MSG_WAITALL, or if the socket is in a non-blocking mode, then this call will fail with WSAEOPNOTSUPP. Also, if MSG_WAITALL is specified along with MSG_OOB, MSG_PEEK, or MSG_PARTIAL, then this call will fail with WSAEOPNOTSUPP. This flag is not supported on datagram sockets or message-oriented CO sockets.

For message-oriented sockets, the MSG_PARTIAL bit is set in the lpFlags parameter if a partial message is received. If a complete message is received, MSG_PARTIAL is cleared in lpFlags. In the case of delayed completion, the value pointed to by lpFlags is not updated. When completion has been indicated, the application should call WSAGetOverlappedResult and examine the flags indicated by the lpdwFlags parameter.

Overlapped Socket I/O

If an overlapped operation completes immediately, WSARecv returns a value of zero and the lpNumberOfBytesRecvd parameter is updated with the number of bytes received and the flag bits indicated by the lpFlags parameter are also updated. If the overlapped operation is successfully initiated and will complete later, WSARecv returns SOCKET_ERROR and indicates error code WSA_IO_PENDING. In this case, lpNumberOfBytesRecvd and lpFlags are not updated. When the overlapped operation completes, the amount of data transferred is indicated either through the cbTransferred parameter in the completion routine (if specified), or through the lpcbTransfer parameter in WSAGetOverlappedResult. Flag values are obtained by examining the lpdwFlags parameter of WSAGetOverlappedResult.

The WSARecv function can be called from within the completion routine of a previous WSARecv, WSARecvFrom, WSASend or WSASendTo function. For a given socket, I/O completion routines will not be nested. This permits time-sensitive data transmissions to occur entirely within a preemptive context.

The lpOverlapped parameter must be valid for the duration of the overlapped operation. If multiple I/O operations are simultaneously outstanding, each must reference a separate WSAOVERLAPPED structure.

If the lpCompletionRoutine parameter is NULL, the hEvent parameter of lpOverlapped is signaled when the overlapped operation completes if it contains a valid event object handle. An application can use WSAWaitForMultipleEvents or WSAGetOverlappedResult to wait or poll on the event object.

If lpCompletionRoutine is not NULL, the hEvent parameter is ignored and can be used by the application to pass context information to the completion routine. A caller that passes a non-NULLlpCompletionRoutine and later calls WSAGetOverlappedResult for the same overlapped I/O request may not set the fWait parameter for that invocation of WSAGetOverlappedResult to TRUE. In this case the usage of the hEvent parameter is undefined, and attempting to wait on the hEvent parameter would produce unpredictable results.

The completion routine follows the same rules as stipulated for Windows file I/O completion routines. The completion routine will not be invoked until the thread is in an alertable wait state such as can occur when the function WSAWaitForMultipleEvents with the fAlertable parameter set to TRUE is invoked.

The prototype of the completion routine is as follows:

void CALLBACK CompletionROUTINE(
  IN DWORD dwError, 
  IN DWORD cbTransferred, 
  IN LPWSAOVERLAPPED lpOverlapped, 
  IN DWORD dwFlags
);

CompletionRoutine is a placeholder for an application-defined or library-defined function name. The dwError specifies the completion status for the overlapped operation as indicated by lpOverlapped. The cbTransferred parameter specifies the number of bytes received. The dwFlags parameter contains information that would have appeared in lpFlags if the receive operation had completed immediately. This function does not return a value.

Returning from this function allows invocation of another pending completion routine for this socket. When using WSAWaitForMultipleEvents, all waiting completion routines are called before the alertable thread's wait is satisfied with a return code of WSA_IO_COMPLETION. The completion routines can be called in any order, not necessarily in the same order the overlapped operations are completed. However, the posted buffers are guaranteed to be filled in the same order in which they are specified.

If you are using I/O completion ports, be aware that the order of calls made to WSARecv is also the order in which the buffers are populated. WSARecv should not be called on the same socket simultaneously from different threads, because it can result in an unpredictable buffer order.

Example Code

The following example shows how to use the WSARecv function in overlapped I/O mode.

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>

#pragma warning(disable: 4127)      // Conditional expression is a constant

#define DATA_BUFSIZE 4096

void __cdecl main(int argc, char **argv) 
{
    WSADATA wsd;
    struct addrinfo *result = NULL,
        *ptr = NULL,
        hints = {0};
    WSAOVERLAPPED RecvOverlapped = {0};
    SOCKET ConnSocket = INVALID_SOCKET;
    WSABUF DataBuf;
    DWORD RecvBytes, Flags;
    char buffer[DATA_BUFSIZE];
    int err, rc;

    if (argc != 2) {
        fprintf(stderr, "usage: %s server-name\n", argv[0]);
        return;
    }

    // Load Winsock
    rc = WSAStartup(MAKEWORD(2,2), &wsd);
    if (rc != 0) {
        fprintf(stderr, "Unable to load Winsock: %d\n", rc);
        return;
    }

    // Initialize the hints to retrieve the server address for IPv4
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    rc = getaddrinfo(argv[1], "27015", &hints, &result);
    if (rc != 0) {
        fprintf(stderr, "getaddrinfo failed: %d\n", rc );
        return;
    }

    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

        ConnSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        if (ConnSocket == INVALID_SOCKET) {
            fprintf(stderr, "socket failed: %d\n", WSAGetLastError());
            freeaddrinfo(result);
            return;
        }
    
        rc = connect(ConnSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (rc == SOCKET_ERROR) {

            if (WSAECONNREFUSED == (err = WSAGetLastError())) {
                closesocket(ConnSocket);
                ConnSocket = INVALID_SOCKET;
                continue;
            }
            fprintf(stderr, "connect failed: %d\n", err);
            freeaddrinfo(result);
            closesocket(ConnSocket);
            return;
        }
        break;
    }
   	if ( ConnSocket == INVALID_SOCKET ) {
		      fprintf(stderr, "Unable to establish connection with the server!\n");
		      freeaddrinfo(result);
		      return;
	   }

    printf("Client connected...\n");

    // Create an event handle and setup an overlapped structure.
    RecvOverlapped.hEvent = WSACreateEvent();
    if (RecvOverlapped.hEvent  == NULL) {
        fprintf(stderr, "WSACreateEvent failed: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ConnSocket);
        return;
    }

    DataBuf.len = DATA_BUFSIZE;
    DataBuf.buf = buffer;

    // Call WSARecv until the peer closes the connection
    // or until an error occurs
    while(1) {

        Flags = 0;
        rc = WSARecv(ConnSocket, &DataBuf, 1, &RecvBytes, &Flags, &RecvOverlapped, NULL);
        if ( (rc == SOCKET_ERROR) && (WSA_IO_PENDING != (err = WSAGetLastError()))) {
            fprintf(stderr, "WSARecv failed: %d\n", err);
            break;
        }

        rc = WSAWaitForMultipleEvents(1, &RecvOverlapped.hEvent, TRUE, INFINITE, TRUE);
        if (rc == WSA_WAIT_FAILED) {
            fprintf(stderr, "WSAWaitForMultipleEvents failed: %d\n", WSAGetLastError());
            break;
        }

        rc = WSAGetOverlappedResult(ConnSocket, &RecvOverlapped, &RecvBytes, FALSE, &Flags);
        if (rc == FALSE) {
            fprintf(stderr, "WSARecv operation failed: %d\n", WSAGetLastError());
            break;
        }

        printf("Read %d bytes\n", RecvBytes);

        WSAResetEvent(RecvOverlapped.hEvent);

        // If 0 bytes are received, the connection was closed
        if (RecvBytes == 0 )
            break;
    }

    WSACloseEvent(RecvOverlapped.hEvent);
    closesocket(ConnSocket);
    freeaddrinfo(result);

    WSACleanup();

    return;
}

Requirements

Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header Winsock2.h
Library Ws2_32.lib
DLL Ws2_32.dll

See Also


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理