Share via


클라이언트에서 데이터 보내기 및 받기

다음 코드는 연결이 설정되면 클라이언트에서 사용하는 sendrecv 함수를 보여 줍니다.

클라이언트

#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);

sendrecv 함수는 각각 보내거나 받은 바이트 수의 정수 값 또는 오류를 반환합니다. 또한 각 함수는 활성 소켓, char 버퍼, 보내거나 받을 바이트 수 및 사용할 플래그와 같은 매개 변수를 사용합니다.

다음 단계: 클라이언트 연결 끊기

윈삭과 함께하는 시작

Winsock 클라이언트 애플리케이션

소켓에 연결