如何在winsock编程中从recv()获取确切的消息? 我在C++中开发了一个使用Winsock的服务器客户端应用程序,并有问题。

如何在winsock编程中从recv()获取确切的消息? 我在C++中开发了一个使用Winsock的服务器客户端应用程序,并有问题。,c++,winsock,C++,Winsock,为了通过服务器从客户端获取消息,我使用下面的代码 int result; char buffer[200]; while (true) { result = recv(client, buffer, 200, NULL); if (result > 0) cout << "\n\tMessage from client: \n\n\t" << message << ";"; } 我遗漏了什么?结果告诉您收到了多少字节

为了通过服务器从客户端获取消息,我使用下面的代码

int result;
char buffer[200];

while (true)
{
    result = recv(client, buffer, 200, NULL);

    if (result > 0)
        cout << "\n\tMessage from client: \n\n\t" << message << ";";
}

我遗漏了什么?

结果告诉您收到了多少字节
recv
不添加终止符,因为一般情况下,网络数据是二进制数据,可能无法用作C样式字符串

如果您知道消息不包含终止字符,您可以自己添加终止符:

buffer[result] = 0;  // make sure the buffer is large enough
或从中生成字符串(或向量,或其他内容):


请注意,您收到的可能不是一条“消息”,特别是当您使用TCP之类的流协议时。它可能包含多条消息,或者只是一条消息的开头。

由于
recv
可能接收的字节数没有您告诉它的那么多,因此您通常使用一个函数 这样可以接收指定数量的字节。修改自

int-receiveall(int-s,char*buf,int*len)
{
int total=0;//我们收到了多少字节
int bytesleet=*len;//我们还有多少要接收
int n=-1;
而(总计<*len){
n=recv(s,buf+总计,字节左,0);

如果(n您没有初始化缓冲区

char buffer[200] = {0};

while (true)
{
    result = recv(client, buffer, 200, NULL);

    if (result > 0)
        cout << "\n\tMessage from client: \n\n\t" << message << ";";
    memset(buffer, 0, 200);
}
char缓冲区[200]={0};
while(true)
{
结果=recv(客户端,缓冲区,200,空);
如果(结果>0)
coutmemset(&receive[0],0,sizeof(receive));

要清除缓冲区

如果你想要一个空终止符,你必须自己添加一个。谢谢。空终止符到底是什么?让我们假设我添加了一个空终止符或类似的东西。我如何从缓冲区中检索字符串?你能给我看一个示例代码吗?通过网络发送以空终止的字符串邀请各种f安全问题。从头开始编写协议是一项艰巨的任务。使用google协议缓冲区之类的东西来编码/解码数据包的内容,可以节省大量的工作。std::string str(buffer);True Alan,my error.memcpy(buffer+result,“\0”,1);//我想这应该行得通。实际上,我通过在客户端发送的消息末尾添加空终止符“\0”解决了这个问题。@user3530012:是的,但一般来说,您应该记住,
recv
可能不会收到您告诉它的所有数据(有关详细信息,请阅读我提供的链接)请在您的答案中添加更多描述。
std::string message_str(message, result);
int receiveall(int s, char *buf, int *len)
{
    int total = 0;        // how many bytes we've received
    int bytesleft = *len; // how many we have left to receive
    int n = -1;

    while(total < *len) {
        n = recv(s, buf+total, bytesleft, 0);
        if (n <= 0) { break; }
        total += n;
        bytesleft -= n;
    }

    *len = total; // return number actually received here

    return (n<=0)?-1:0; // return -1 on failure, 0 on success
} 
char buffer[200] = {0};

while (true)
{
    result = recv(client, buffer, 200, NULL);

    if (result > 0)
        cout << "\n\tMessage from client: \n\n\t" << message << ";";
    memset(buffer, 0, 200);
}