簡體   English   中英

在Linux中使用TCP套接字傳輸映像

[英]Transferring an Image using TCP Sockets in Linux

我試圖使用Linux使用TCP套接字傳輸圖像。 我已經多次使用代碼來傳輸少量數據,但是當我嘗試傳輸圖像時,它只轉移了前三分之一。 Linux中的tcp套接字是否有可能存在最大緩沖區大小? 如果是這樣我怎么能增加它? 是否有以編程方式執行此操作的函數?

我猜想當你從套接字讀取時,問題出在接收端。 TCP是基於流的協議,不知道數據包或消息邊界。

這意味着當您執行讀取操作時,可能會獲得比您請求的更少的字節數。 例如,如果您的圖像為128k,則在第一次讀取時可能只會獲得24k,需要您再次讀取以獲取其余數據。 它是一個圖像的事實是無關緊要的。 數據就是數據。

例如:

int read_image(int sock, int size, unsigned char *buf) {
   int bytes_read = 0, len = 0;
   while (bytes_read < size && ((len = recv(sock, buf + bytes_read,size-bytes_read, 0)) > 0)) {
       bytes_read += len;
   }
   if (len == 0 || len < 0) doerror();
   return bytes_read;
}

TCP會將數據分段發送,因此您無法保證只需一次讀取即可獲得所有數據(盡管它保證按照您發送的順序保留)。 在獲得所有數據之前,您基本上必須多次閱讀。 它也不知道你在接收器端發送了多少數據。 通常,您首先發送固定大小的“長度”字段(例如,總是8個字節),以便您知道有多少數據。 然后你繼續閱讀並構建一個緩沖區,直到你得到那么多字節。

所以發件人看起來像這樣(偽代碼)

int imageLength;
char *imageData;

// set imageLength and imageData

send(&imageLength, sizeof(int));
send(imageData, imageLength);

接收器看起來像這樣(偽代碼)

int imageLength;
char *imageData;

guaranteed_read(&imageLength, sizeof(int));
imageData = new char[imageLength];
guaranteed_read(imageData, imageLength);

void guaranteed_read(char* destBuf, int length)
{
    int totalRead=0, numRead;
    while(totalRead < length)
    {
        int remaining = length - totalRead;
        numRead = read(&destBuf[totalRead], remaining);
        if(numRead > 0)
        {
            totalRead += numRead;
        }
        else
        {
            // error reading from socket
        }
    }
}

顯然我沒有實際的套接字描述符,你需要為所有這些添加大量的錯誤檢查。 它並不意味着完整,更多的是為了展示這個想法。

1個單個IP數據包的最大大小為65535,非常接近您所命中的數字。 我懷疑這是巧合。

暫無
暫無

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

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