簡體   English   中英

C winsock功能發送所有消息數據

[英]C winsock function to send all message data

我正在使用WSA用c編寫服務器,該服務器將處理多個客戶端。 該協議是我自己定義的,而我遇到的問題是如何確保將整個消息實際發送給客戶端。

send一次消息,然后檢查實際傳輸的字節數。 然后,如果沒有,我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;
    }
}

這是我自己的項目之一的工作代碼。 注釋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