利用 TCP 完成檔案傳輸的設計

2021-10-01 21:05:55 字數 3835 閱讀 9593

輸入檔案路徑,利用 tcp 實現客戶檔案向伺服器的傳輸,並實現對 tcp 的基本封裝

(1)建立 socket

(2)確定伺服器 scokaddr_in 結構體

(3)點分十進位制 ip 轉換

(4)使用 bind 繫結套接字

(5)使用 listen 監聽

(6)使用 accept 接受連線請求

(7)accept 返回新的套接字描述符

(8)使用 recv 接收傳來的資料(檔案路徑)

(9)開啟檔案,這裡需要檔名

(10)從該字串獲取檔名

(11)使用 recv 接收檔案內容

(12)判斷 recv 函式返回的狀態

(13)將接收到的內容放入緩衝區

(14)將緩衝區內容寫入檔案

(15)關閉檔案

(16)關閉 socket

(1)建立 socket

(2)確定伺服器 scokaddr_in 結構體

(3)點分十進位制 ip 轉換

(4)使用 connect 連線

(5)開啟檔案

(6)準備緩衝區

(7)緩衝區初始化置空

(8)將檔案內容讀入緩衝區

(9)使用 send 將緩衝區內容傳送到伺服器

(10)檔案內容傳送完成

(11)關閉檔案

(12)關閉 socket

#include 

#include

#include

#include

#include

#include

#include

#define port 1111

// 設定埠號

#define listenq 10

// 設定監聽佇列長度

#define buffsize 1024

// 設定緩衝區大小

#define file_buffsize 100

// 設定檔案緩衝區大小

#define end_flag "end"

// 結束標記

intpassivetcp()

intmain()

else

;//做中間臨時儲存

cnt ++

;printf

("===connect success %d===\n"

, cnt)

;// 處理考慮有多個檔案的情況

while(1

)printf

("#> %s\n"

, filename)

;// 對檔名進行處理

int t =

(int)(

strchr

(filename,

'.')

- filename)

;// 計算'.'的下標

// 判斷檔案有無字尾

if( t <0)

else

file *fp =

fopen

(filename,

"w")

;//建立檔案

printf

("transport start\n");

int n;

// 接收檔案內容,並寫入開啟的檔案中,直到檔案結尾

while

((n =

recv

(clie_fd, buffer, buffsize,0)

)>0)

fwrite

(buffer,

sizeof

(char

), n, fp)

;// buffer 清零

memset

(buffer,

0, buffsize);}

printf

("transport finish\n");

printf

("_______________________\n");

// 關閉檔案

fclose

(fp);}

// 關閉連線新建套接字

close

(clie_fd)

;printf

("===connect close %d===\n"

, cnt);}

}// 關閉伺服器套接字

close

(serv_fd)

;return0;

}

#include 

#include

#include

#include

#include

#include

#include

#define port 1111

// 設定埠號

#define ip "127.0.0.1"

// 設定ip

#define buffsize 1024

// 設定緩衝區大小

#define file_buffsize 100

#define end_flag "end"

intmain

(int argc,

char

*ar**)

else

}//輸入要傳送的檔名,檔案確保在根目錄下

else

}for

(int i =

0; i < cnt; i ++

) file* fp =

fopen

(file_name_t[i]

,"r");

// 以讀的方式開啟檔案

if(fp == null)

else

printf

("transport finish\n");

sleep

(0.5);

send

(clie_fd, end_flag,

sizeof

(end_flag),0

);// 傳送結束標誌

printf

("$> %s\n\n"

, end_flag);}

// 關閉檔案

fclose

(fp)

;sleep

(0.5);

}send

(clie_fd, end_flag,

sizeof

(end_flag),0

);// 傳送結束標誌

printf

("$> %s\n"

, end_flag);}

printf

("********************=\n");

// 關閉套接字

close

(clie_fd)

;return0;

}

傳輸前客戶端根目錄下儲存著我們

傳輸的檔案 wct.txt

Python完成檔案傳輸

一 什麼是tftp?tftp trivial file transfer protocol,簡單檔案傳輸協議 是tcp ip協議族中的乙個用來在客戶機與伺服器之間進行簡單檔案傳輸的協議,提供不複雜 開銷不大的檔案傳輸服務。埠號為69。二 tftp伺服器 客戶端傳輸原理 1 首先,客戶端傳送乙個讀寫請...

tcp檔案傳輸

include include include include include include include include define buffer size 100 1024 1024 define file name max size 512 intmain int argc,char a...

TCP檔案傳輸(一)

最近在做網路抓包和檔案傳輸,今天遇到乙個奇怪的現象,自己查了半天也沒搞清楚,導致花了乙個下午時間就只實現了檔名和檔案長度的傳送,首先給出檔案傳輸的客戶端和伺服器端 一 客戶端 1 winsock com元件初始化和釋放 include stdafx.h ifndef winsock startup ...