簡體   English   中英

有什么方法可以檢查在 C 的緩沖區中寫入了多少數據/字節

[英]Is there any way to check how much data/bytes is written in buffer in C

有什么方法可以檢查在確切的時刻在緩沖區中寫入了多少字節? 我想使用socket.send()動態設置我通過套接字發送的數據量。 現在我有問題,假設我的文件是 200KB,我的緩沖區設置為 24KB,所以我需要發送 9 個包,我的 output 文件是 216KB 大,而不是 200KB 作為輸入。 有沒有辦法處理這些空字節?

socket.send我不知道。 我假設您的意思是在某些socket(7)上使用send(2 ) 。

在許多情況下(想想一些tcp(7)流量通過幾個 Wifi 路由器),數據包可能會被分段 因此,一側的給定send(2)可能對應於接收側的多個recv(2) ,反之亦然。

然后你需要以某種方式管理你的數據包數據(例如計數和緩沖發出的數據,以及接收的數據)。 在實踐中,您需要一些關於它們的文檔化約定。 HTTPSMTPJSONRPCONCRPCMQTT可能是鼓舞人心的。

您會找到可能有用的庫。 例如libcurlWtQtPOCOlibonion 它們是開源的,因此您可以研究它們的源代碼。

You could also study the source code of well known open source servers, such as lighttpd , postfix , etc... or take inspiration from other open source projects coded in C++, including The Clang static analyzer , RefPerSys or fish or many others on githubgitlab

您將問題標記為CC++但它們是非常不同的語言。 有關更多信息,請參閱此參考

順便說一句, Clang static 分析儀應該會有所幫助。 If you compile your C++ code with a recent GCC , be sure to enable all warnings and debug info, so compile with g++ -Wall -Wextra -g (and later use the GDB debugger)

有什么方法可以檢查在 C 的緩沖區中寫入了多少數據/字節

是的,因為send(2)write(2) (以及recv(2)read(2) )都在成功時返回字節數。

您的事件循環將處理它們(計數字節、管理緩沖區)並使用poll(2)或其他一些多路復用系統調用。 在這種情況下,您可以找到有用的庫( libevlibevent等...)

另請注意,2020 年我們到處都有 UTF-8 因此,即使對於文本輸入,某些字母(如俄語 Ы 或法語 à 或您居住的城市波茲南的最后一個字母......)可能需要超過一個字節。 當您發送文本信息時,這會增加代碼的復雜性。

最好的辦法是自己計算這些字節數,因為您總是知道要寫入多少字節。

如果您有 200KB 要發送,並且一次可以發送 24KB,那么它只是(在偽代碼中):

const int chunkSize = 24*1024;
const int inputSize = 200*1024;

char input[inputSize];   // N.B. VLAs not actually valid C++; this is pseudo-code
int bytesSent = 0;

while (true)
{
   const int bytesRemaining = inputSize - bytesSent;
   const int bytesToSend = std::min(chunkSize, bytesRemaining);
   
   if (bytesToSend == 0)
   {
      // Done!
      break;
   }
   
   const int bytesWritten = send(&input[bytesSent], bytesToSend);
   
   if (bytesWritten == 0)  // I'm assuming 0 written means error; adjust for your API
   {
      // Error! Handle it.
      break;
   }
   
   bytesSent += bytesWritten;
   
   if (bytesSent > inputSize)
   {
      // Something went horribly wrong
      break;
   }
}

簡單的。

(實際上,您可能應該使用一些無符號類型,例如std::size_t ,而不是int ,除非您的send在錯誤時返回一些負值。)

bytesToSend是這里的關鍵。 您可能不想在最后一次迭代中發送“完整”塊。 這就是您額外的 16KB 的來源:您的輸入不是塊大小的精確倍數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM