Linux下用UDP實現檔案傳輸

2021-09-11 22:01:45 字數 2827 閱讀 2810

原文:

udp程式設計框圖

udp協議中伺服器和客戶端的互動存在於資料的收發過程中。

進行網路資料收發的時候,伺服器和客戶端的資料是對應的:客戶端傳送資料的動作,對伺服器來說是接收資料的動作;客戶端接收資料的動作,對伺服器來說是傳送資料的動作。

實現檔案的傳輸大概分為這幾個步驟:

客戶端讀檔案,將內容放在client_buffer中

客戶端通過sendto傳送client_buffer中的資料

伺服器端通過recvfrom對資料進行接收,存到server_buffer中

將資料寫入檔案中,關閉檔案,關閉套接字

直接來**:

伺服器端:

// udp_file_server.c

#include #include #include #include #include #include #include #include #define buffer_size 1024

int main()

else

memset(&server,0,sizeof(server)); //清空server結構體

server.sin_family= af_inet;

server.sin_addr.s_addr = htonl(inaddr_any);

server.sin_port = htons(8888);

if((bind(sockfd,(struct sockaddr*)&server,sizeof(server)))==-1)

else

while(1)

else

else

break;

} strcpy(filename,filepath+(strlen(filepath)-k)+1);

}printf("filename :%s\n",filename);

fp = fopen(filename,"w");

if(fp!=null)

writelength = fwrite(buffer,sizeof(char),filetrans,fp);

if(filetrans < buffer_size)

else

printf("continue\n");

bzero(buffer,buffer_size);

}printf("recv finished!\n");

fclose(fp);

}else

}close(sockfd);

return 0;

}

客戶端:

//   udp_file_client

#include #include #include #include #include #include #include #include #define buffer_size 1024

int main()

memset(&server,0,sizeof(server));

server.sin_family= af_inet;

server.sin_port = htons(8888);

if(inet_pton(af_inet,"127.0.0.1",&server.sin_addr)<0)

printf("file path:\n");

scanf("%s",filepath);//get filepath

fp = fopen(filepath,"r");//opne file

if(fp==null)

printf("filepath : %s\n",filepath);

lenpath = sendto(sockcd,filepath,strlen(filepath),0,(struct sockaddr *)&server,addrlen);// put file path to sever

if(lenpath<0)

else

//sleep(1);

printf("begin send data...\n");

int times = 1;

while((filetrans = fread(buffer,sizeof(char),buffer_size,fp))>0)

else

if(filetrans < buffer_size) break;

bzero(buffer,buffer_size);

}//printf("filetrans =%d\n",filetrans);

fclose(fp);

close(sockcd);

return 0;

}

在實現過程中,出現了這樣一種情況:

在收發大檔案時,客戶端傳送正常,伺服器總是只能收到前一部分檔案內容,後面的全部丟包。

在經過各種除錯之後,發現在發資料時,客戶端一直在迴圈不斷的傳送資料,傳送太快,而伺服器來不及接收 。

在每次傳送資料時,sleep一會,這個問題就解決了。

效果圖:

執行......

結果:

Linux下UDP傳輸檔案示例

linux在嵌入式作業系統中所佔的比例是非常大的,現將自己在學習中的udp的部分 分享給大家,本文主要運用udp來傳輸檔案,如下 send.c include include include include include include include define ip 192.168.0.99...

linux下C 實現UDP通訊

簡要介紹udp原理,通過 例項講解。本篇部落格不強調server跟client 的概念,重在實現雙方互通。收的一方 socket bind recvfrom close 發的一方 socket sendto close 只有收資料的一方需要bind 而傳送的一方不需要bind 由上圖可以看出,bin...

linux下udp大檔案傳輸

近日小弟做了個linux下使用者資料報協議大檔案傳輸程式發上來與大家共勉。在 redhat 9.0 下編譯通過。最大測試無差錯傳輸檔案 288m 最大測試傳輸速度 6.5m s 可能這裡並不需要這種型別的帖子,但希望各位能代小弟轉貼,因為網路上很難搜尋到這種可以解決丟包問題的 級實現方法,希望每乙個...