Windows Dev Center

Receiving and Sending Data on the Server

The following code demonstrates the recv and send functions used by the server.

To receive and send data on a socket

#define DEFAULT_BUFLEN 512

char recvbuf[DEFAULT_BUFLEN];
int iResult, iSendResult;
int recvbuflen = DEFAULT_BUFLEN;

// Receive until the peer shuts down the connection
do {

    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        printf("Bytes received: %d\n", iResult);

        // Echo the buffer back to the sender
        iSendResult = send(ClientSocket, recvbuf, iResult, 0);
        if (iSendResult == SOCKET_ERROR) {
            printf("send failed: %d\n", WSAGetLastError());
            return 1;
        printf("Bytes sent: %d\n", iSendResult);
    } else if (iResult == 0)
        printf("Connection closing...\n");
    else {
        printf("recv failed: %d\n", WSAGetLastError());
        return 1;

} while (iResult > 0);

The send and recv functions both return an integer value of the number of bytes sent or received, respectively, or an error. Each function also takes the same parameters: the active socket, a char buffer, the number of bytes to send or receive, and any flags to use.

Next Step: Disconnecting the Server

Related topics

Getting Started With Winsock
Winsock Server Application
Accepting a Connection



Community Additions

© 2015 Microsoft