简体   繁体   English

C winsock功能发送所有消息数据

[英]C winsock function to send all message data

I'm writing a server in c using WSA that will handle multiple clients. 我正在使用WSA用c编写服务器,该服务器将处理多个客户端。 The protocol is something I defined on my own, and the part I'm having trouble with is how to make sure the whole message is actually being sent to the client. 该协议是我自己定义的,而我遇到的问题是如何确保将整个消息实际发送给客户端。

I send my message once, and than I check how many bytes where actually transferred. send一次消息,然后检查实际传输的字节数。 Then, if not, I send again, and as the length of the data that I will now send I use unsentBytes (see in code). 然后,如果没有,我send再次send ,并且由于现在发送的数据长度,我使用了unsentBytes (请参见代码)。 My problem is that when I try to send the extra bytes that weren't sent, I am currently sending again the entire message. 我的问题是,当我尝试发送未发送的额外字节时,我目前正在再次发送整个消息。 How can I send only the remaining part of the message? 如何仅发送邮件的其余部分?

I know I can send only 1 char at a time, and stop recieving on the client side when I get to the end of the message, but I think I can do it like this as well and that it's better. 我知道我一次只能发送1个字符,并且在到达消息末尾时不再在客户端接收消息,但是我想我也可以这样做,而且更好。

Is this the right logic to use? 这是使用正确的逻辑吗?

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

Here's working code from one of my own projects. 这是我自己的项目之一的工作代码。 Note data + count to offset into the data. 注释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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM