清除缓冲区-Winsock

时间:2012-07-26 05:01:35

标签: c++ sockets client buffer winsock

这是我在Windows中使用winsock在C ++中创建的客户端程序的代码。

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include<sstream>
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFLEN 512
#pragma comment(lib,"WS2_32.lib");

struct addrinfo *result = NULL,
         *ptr = NULL,
         hints;

int main()
{
WSAData wsadata;
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
char *sendbuf = "1,2,3,4!!";
char recvbuf[512];



iResult=WSAStartup(MAKEWORD(2,2),&wsadata);
if(iResult!=0)
{
    std::cout<<"WSAStartup failed"<<iResult<<std::endl;
    getchar();
    return 1;
}

ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

char arr[20]="localhost";

iResult = getaddrinfo(arr, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
{
    std::cout<<"getaddrinfo failed: "<<iResult;
    getchar();
    WSACleanup();
    return 1;
}

SOCKET ConnectSocket = INVALID_SOCKET;
ptr=result;
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
ptr->ai_protocol);

if (ConnectSocket == INVALID_SOCKET)
{
    std::cout<<"Error at socket(): "<<WSAGetLastError();
    getchar();
    freeaddrinfo(result);
    WSACleanup();
    return 1;
}

iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
    closesocket(ConnectSocket);
    ConnectSocket = INVALID_SOCKET;
}

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET) 
{
    std::cout<<"Unable to connect to server!"<<std::endl;
    getchar();
    WSACleanup();
    return 1;
}



for(;;)
{
int i=15;
int x=12;
int z=1;
iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
std::cout<<"Recieved data: "<<recvbuf<<std::endl;
}

iResult = shutdown(ConnectSocket, SD_SEND);

if (iResult == SOCKET_ERROR) 
{
    std::cout<<"shutdown failed: "<<WSAGetLastError();
    getchar();
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}

if (iResult == 0)
    std::cout<<"Connection closed\n";
else
    std::cout<<"recv of client failed: "<<WSAGetLastError();

iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) 
{
    std::cout<<"shutdown failed: "<<WSAGetLastError();
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}

closesocket(ConnectSocket);
WSACleanup();
getchar();
return 0;
}

我收到的信息很好。唯一的问题是我想在每次收到一些数据时清除缓冲区。 如果我发送a,b,c,d,则当前代码的输出类似于

A,B,C,d

AA,BB,CC,DD

AAA,BBB,CCC,DDD

虽然我希望我的输出为a,b,c,d,因为它会一次又一次地接收这些信息。怎么做?

1 个答案:

答案 0 :(得分:0)

您提供的代码看起来像无限循环:

for(;;)
{
int i=15;
int x=12;
int z=1;
iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
std::cout<<"Recieved data: "<<recvbuf<<std::endl;
}

最重要的是,它输出recvbuf就好像它是一个字符串,但不能保证它会被\0终止,并且如果你真的读到它,可能会导致未定义的行为完整DEFAULT_BUFLEN个字节的数据。我建议在打印前进行string转换。但在此之前,应检查recv的返回值。

iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
if (iResult <= 0) break;
std::cout<<"Received data: " <<std::string(recvbuf,iResult)<<std::endl;