如何从recv()在winsock编程中获得确切的消息? [英] How to get the exact message from recv() in winsock programming?

查看:97
本文介绍了如何从recv()在winsock编程中获得确切的消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的C ++和有问题使用Winsock的一个服务器 - 客户端应用程序。

I'm developing a server-client application using Winsock in c++ and have a problem.

有关服务器从客户端收到消息我使用的代码

For getting the message from the client by the server I use the code below.

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 << ";";
}



我发送消息Hello,从客户机到服务器。然而,缓冲区实际上是这样的:

I send the message "Hello" from the client to the server. However the buffer is actually this:

HelloÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ

我缺少什么?

推荐答案

由于的recv ,你告诉它可能无法获得尽可能多的字节,通常使用的函数
这样接收的字节指定数量。从这里 修改

Since recv might not receive as many bytes as you told it, you typically use a function like this to receive specified number of bytes. Modified from here

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
} 

null如果接收到非空结束的字符串,则终止字符串。

It's up to you to null terminate the string if you receive string which is not null terminated.

这篇关于如何从recv()在winsock编程中获得确切的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆