使用 TCP 从客户端向服务器发送字节的问题

发布于 2024-10-19 15:05:20 字数 939 浏览 4 评论 0原文

我的 send() 和 recv() 看起来像这样:

int Send(const char* buffer, int size)
{
    cout << "SIZE: " << size << endl;
    int offset;
    while(offset < size)
    {
        int n = ::send(getSocket(), buffer + offset, size - offset, 0);
        if(n == SOCKET_ERROR)
        {
            break;
        }
        offset += n;
        if(offset != size)
        {
            Sleep(1);
        }
    }
    return offset;
}

int Recv(char* buffer, int size)
{
    int n = ::recv(getSocket(), buffer, size, 0);
    if(n == SOCKET_ERROR)
    {
        cout << "Error receiving data" << endl;
    }
    if(n == 0)
    {
        cout << "Remote host closed connection" << endl;
    }
    return n;
}

但我的输出显示发送了很多字节,这对我来说似乎很奇怪:

Received from client: 669
Sent to web server: 3990336

所以它应该发送 669 个字节,那么它从哪里得到 3990336 ?这是某种错误还是?

谢谢。

My send() and recv() looks like this:

int Send(const char* buffer, int size)
{
    cout << "SIZE: " << size << endl;
    int offset;
    while(offset < size)
    {
        int n = ::send(getSocket(), buffer + offset, size - offset, 0);
        if(n == SOCKET_ERROR)
        {
            break;
        }
        offset += n;
        if(offset != size)
        {
            Sleep(1);
        }
    }
    return offset;
}

int Recv(char* buffer, int size)
{
    int n = ::recv(getSocket(), buffer, size, 0);
    if(n == SOCKET_ERROR)
    {
        cout << "Error receiving data" << endl;
    }
    if(n == 0)
    {
        cout << "Remote host closed connection" << endl;
    }
    return n;
}

But my output show kind of many bytes sent that seems strange to me:

Received from client: 669
Sent to web server: 3990336

So it should supose to sent 669 bytes, so from where did it get 3990336 ? It is some kind of error or ?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

亽野灬性zι浪 2024-10-26 15:05:20

您是否注意到 int offset; 没有初始化?

Did you notice that int offset; is not initialize ?

浅语花开 2024-10-26 15:05:20
  1. 您必须将 offset 初始化为零。否则它可以是任何随机值。
  2. 您不需要 Sleep,因为 send 调用被阻塞。
  3. 您发送的缓冲区可能会被分割。因此,例如,如果您发送 2K 缓冲区,则可以将其分为两部分 - 1.5K 和 0.5K,因此您必须在客户端执行多次读取。 MTU 通常设置为 1500 字节。
  1. You have to initialize offset with zero. Otherwise it could be any random value.
  2. You do not need Sleep as send call is blocking.
  3. Buffer that you are sending could be split. So if you send, for example, 2K buffer, you could get it in two parts - 1.5K and 0.5K, so you have to perform multiple reads on a client side. MTU is usually set to 1500 bytes.
微凉 2024-10-26 15:05:20

也许这只是您的(精简的?)示例代码,但您从未真正初始化 offset。它可能具有任何值,例如-5000,并且将导致循环发送5669 字节。

Maybe it's just your (stripped down?) example code, but you never actually initialize offset. It might have any value, e.g. -5000 and will cause the loop to send 5669 bytes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文