gpt4 book ai didi

sockets - 了解套接字接收行为

转载 作者:行者123 更新时间:2023-12-03 11:57:13 24 4
gpt4 key购买 nike

我正在阅读recv http://linux.die.net/man/2/recv的联机帮助页,但它并没有真正回答我的问题,因此希望我能在这里得到一些答案。

我这样称呼recv:

numBytes = ::recv(getSocketId(), pData, nSize, MSG_DONTWAIT);

现在的问题是:
  • 当程序包大于缓冲区时,recv将读取最多nSize个字节并将其放在内存位置。返回值将是nSize,对不对?我可以再次调用recv,直到接收到所有数据为止。
  • 当程序包小于nSize时,rcv将读取尽可能多的字节,然后返回值 =0。还是recv尝试等待直到实际接收到nSize字节?如果我正确理解手册页,我认为情况并非如此(至少我希望如此)。还是recv返回-1并且errno = EAGAIN或EWOULDBLOCK?
  • 如果recv返回-1,则缓冲区会发生什么情况?在这种情况下,它会始终保持不变,还是已经将部分数据放入其中,但是那时我将永远不知道传输了多少字节,所以我认为情况并非如此,对吗?

  • 我想拥有的是,它读取尽可能多的字节,然后返回,从而提供了传输的字节数。在另外的一层中,我将构造实际的消息,而与接收消息的方式无关。但是,我不希望服务器卡在接收调用中,因为我不知道客户端在做什么,并且它不应该有效地将服务器卡在一个连接上。

    最佳答案

    1. When the package is bigger than the buffer, recv will read up to nSize bytes and place it in the memory location. the returnvalue would be nSize, right? I can call recv again until all data is received.


    正确的。

    1. When the package is smaller than nSize rcv will read as many bytes as are available and then return with a value < nSize && >= 0.


    不完全的。如果有数据,它将返回> 0;如果对等方已关闭连接,则返回0;如果有错误,或者没有数据,并且您处于非阻塞模式,则返回-1。

    Or would recv try to wait until nSize bytes were actually received?



    不。

    If I understand the man page correct, I think this is not the case (at least I hope for it).



    正确的。

    Or will recv return with -1 and errno = EAGAIN or EWOULDBLOCK?



    是的,如果您处于非阻塞模式并且没有数据。

    1. If recv returns with -1 what happens to the buffer?


    没有。

    Will it always stay untouched in that case



    是的。

    or could it be that part of the data has already been put into it



    不。如果您有任何数据,您将得到它的长度,而不是-1。

    but then I would never know how many bytes were transfered, so I assume that this is not the case, right?



    正确的。

    关于sockets - 了解套接字接收行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16337934/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com