您的位置:首页 > 其它

Winsock API: recv

2013-03-11 18:01 246 查看
参考MSDN:http://msdn.microsoft.com/en-us/library/windows/desktop/ms740121(v=vs.85).aspx

The recv function receives data from a connected socket or a bound connectionless socket.

Syntax

int recv(

  _In_   SOCKET s,

  _Out_  char *buf,

  _In_   int len,

  _In_   int flags

);

Parameters

s [in]
The descriptor that identifies a connected socket.

buf [out]
A pointer to the buffer to receive the incoming data.

len [in]
The length, in bytes, of the buffer pointed to by the buf parameter.

flags [in]
A set of flags that influences the behavior of this function. See remarks below. See the Remarks section for details on the possible value for this parameter.

Return value

If no error occurs, recv returns the number of bytes received and the buffer pointed to by the
buf parameter will contain this data received. If the connection has been gracefully closed, the return value is zero.

Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling

WSAGetLastError.

Remarks

The recv function is used to read incoming data on connection-oriented sockets, or connectionless sockets. When using a connection-oriented protocol, the sockets must be connected before calling
recv. When using a connectionless protocol, the sockets must be bound before calling
recv.

If the datagram or message is larger than the buffer specified, the buffer is filled with the first part of the datagram, and
recv generates the error
WSAEMSGSIZE. For unreliable protocols (for example, UDP) the excess data is lost; for reliable protocols, the data is retained by the service provider until it is successfully read by calling
recv with a large enough buffer.

If no incoming data is available at the socket, the recv call blocks and waits for data to arrive according to the blocking rules defined for

WSARecv with the MSG_PARTIAL flag not set unless the socket is nonblocking. In this case, a value of SOCKET_ERROR is returned with the error code set to

WSAEWOULDBLOCK. The
select,
WSAAsyncSelect, or
WSAEventSelect functions can be used to determine when more data arrives.

If the socket is connection oriented and the remote side has shut down the connection gracefully, and all data has been received, a
recv will complete immediately with zero bytes received. If the connection has been reset, a
recv will fail with the error
WSAECONNRESET.

Example Code

The following code example shows the use of the recv function.

#define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>

// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main() {

//----------------------
// Declare and initialize variables.
WSADATA wsaData;
int iResult;

SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;

char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;

//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}

//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return 1;
}

//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientService.sin_port = htons( 27015 );

//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( iResult == SOCKET_ERROR) {
closesocket (ConnectSocket);
printf("Unable to connect to server: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}

// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}

printf("Bytes Sent: %ld\n", iResult);

// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}

// Receive until the peer closes the connection
do {

iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());

} while( iResult > 0 );

// cleanup
closesocket(ConnectSocket);
WSACleanup();

return 0;
}


 

 

 

  gracefully   -  简明英汉词典D.J.[ˈ greɪsfʊlɪ]
adv. 优美地;优雅地;雅致地;温文地

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: