这是我在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时,因为它不断地接收此信息。这该怎么做?
最佳答案
您提供的代码看起来像一个无限循环:
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;
关于c++ - 清除缓冲区-Winsock,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11662625/