Share via


Enviando e recebendo dados no cliente

O código a seguir demonstra as funções send e recv usadas pelo cliente depois que uma conexão é estabelecida.

Cliente

#define DEFAULT_BUFLEN 512

int recvbuflen = DEFAULT_BUFLEN;

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

int iResult;

// 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 for sending since no more data will be sent
// the client can still use the ConnectSocket for receiving data
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("shutdown failed: %d\n", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}

// Receive data until the server 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);

As funções send e recv retornam um valor inteiro do número de bytes enviados ou recebidos, respectivamente, ou um erro. Cada função também usa os mesmos parâmetros: o soquete ativo, um buffer char , o número de bytes a serem enviados ou recebidos e quaisquer sinalizadores a serem usados.

Próxima etapa: desconectando o cliente

Introdução com Winsock

Aplicativo cliente Winsock

Conectando-se a um Soquete