【问题标题】:C winsock function to send all message dataC winsock函数发送所有消息数据
【发布时间】:2017-07-22 12:06:27
【问题描述】:

我正在使用 WSA 在c 中编写一个服务器,它将处理多个客户端。协议是我自己定义的,而我遇到问题的部分是如何确保整个消息实际上是发送给客户端的。

send我的消息一次,然后我检查实际传输了多少字节。然后,如果没有,我再次send,作为我现在要发送的数据的长度,我使用unsentBytes(见代码)。 我的问题是,当我尝试发送未发送的额外字节时,我目前正在再次发送整个消息。我怎样才能只发送消息的剩余部分?

我知道我一次只能发送 1 个字符,并且在我到达消息末尾时停止在客户端接收,但我认为我也可以这样做,而且这样会更好。

这是使用正确的逻辑吗?

int send_msg(SOCKET s, char *msg, int msg_len)
{
    int unsentBytes = msg_len;
    int bytesResult = send(s, msg, msg_len, SEND_FLAGS);
    unsentBytes -= bytesResult;
    while (unsentBytes != 0)
    {
        bytesResult = send(s, msg, unsentBytes, SEND_FLAGS); // ### msg is the problem
        unsentBytes -= bytesResult;
    }
}

【问题讨论】:

  • 如果您不需要保留msg 的值(就像发布的代码中的情况一样),您可以在每次发送后说msg += bytesResult;

标签: c winsock winsock2 windows-socket-api


【解决方案1】:

这是我自己项目之一的工作代码。注意data + count 偏移到数据中。

int sendall(int sd, char *data, int length) {
    int count = 0;
    while (count < length) {
        int n = send(sd, data + count, length, 0);
        if (n == -1) {
            return -1;
        }
        count += n;
        length -= n;
    }
    return 0;
}

【讨论】:

  • 感谢您的回答。在使用此代码时,以及在类似的接收代码中 - 我不应该处理我接收/发送 0 字节的选项吗?
  • 如果send 返回零,它将再次尝试。
  • 知道了。那么当返回-1时,究竟是什么意思呢?
  • 表示发生错误。此页面上列出了可能的错误:pubs.opengroup.org/onlinepubs/009695399/functions/send.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多