socket 傳輸檔案

2021-08-31 19:48:05 字數 2072 閱讀 2085

在兩台計算機傳輸檔案之前,必需得先有一台計算機建立套節子連線並繫結乙個固定得埠,並在這個埠偵聽另外一台計算機的連線請求。

socket   =   new   socket(addressfamily.internetwork,sockettype.stream,   protocoltype.tcp);

socket.blocking   =   true   ;

ipendpoint   computernode1   =   new   ipendpoint(serveripadress,   8080);

socket.bind(computernode1);

socket.listen(-1);

當有其他的計算機發出連線請求的時候,被請求的計算機將對每乙個連線請求分配乙個執行緒,用於處理檔案傳輸和其他服務。

while   (   true   )  

} 下面的**展示了listenclient方法是如何處理另外一台計算機傳送過來的請求。首先並對傳送過來的請求字串作出判斷,看看是何種請求,然後決定相應的處理方法。

//取得預儲存的檔名  

string   filename= "test.rar ";  

//遠端主機  

string   hostname=textboxhost.text.trim();  

//埠  

int   port=80;  

//得到主機資訊  

iphostentry   ipinfo=dns.gethostbyname(hostname);  

//取得ipaddress  

ipaddress   ipaddr=ipinfo.addresslist;  

//得到ip  

ipaddress   ip=ipaddr[0];  

//組合出遠端終結點  

ipendpoint   hostep=new   ipendpoint(ip,port);  

//建立socket   例項  

socket   socket=new   socket(addressfamily.internetwork,sockettype.stream,protocoltype.tcp);  

try  

catch(exception   se)  

例子2:

這幾天一直想寫乙個類似qq檔案傳送的東西,上網找了一些資料,都不是很理想,下面我把我的思路和基本實現**說下。

為了把問題說清楚,把一些變數都直接附值了,並沒有通過輸入附值

private string path = "f:";    //要傳送的檔案

private socket s;                             

private void listen()

}catch(nullreferenceexception e)

",e); }

private void set()                       

//建立set函式

while (start != 0)

file.close();    //關閉檔案流

s.close();        //關閉socket

}  catch (nullreferenceexception e)

", e);

}             

}   

這樣檔案傳送的模型就實現了

接下去實現檔案的接收,首先要確定對方傳送檔案的長度,其實上面的那段還要加入傳送檔案長度的功能,實現很簡單,就是傳送int變數end ,然後要求接收**返回乙個boolean確定是否傳送,這裡為了更簡明的說清楚原理並沒有實現

private void get()

file.write(data, 0, 1214134);

//寫入檔案,1214134為檔案大小,可以用socket傳送獲得,**前面已經說明。

s1.close();

file.close();}}

catch(nullreferenceexception e)

",e);}}

socket 傳輸檔案

在兩台計算機傳輸檔案之前,必需得先有一台計算機建立套節子連線並繫結乙個固定得埠,並在這個埠偵聽另外一台計算機的連線請求。socket new socket addressfamily.internetwork,sockettype.stream,protocoltype.tcp socket.blo...

Socket傳輸檔案示例

socket傳輸檔案示例 1 顯示檔案進度 2 可以隨時終止傳輸過程 傳送資料執行緒 uint senddatathread lpvoid lpparam 接收資料執行緒 uint receivedatathread lpvoid lpparam 傳送資料按鈕訊息響應函式 void ctzg004d...

socket檔案傳輸

伺服器 本檔案是伺服器的 include for sockaddr in include for socket include for socket include for printf include for exit include for bzero include for time t an...