system.sockes命名空間了實現 berkeley 套接字接口。通過這個類,我們可以實現網絡計算機之間的消息傳輸和發送.而在我下面要討論的這個議題里,我們將討論的是用套節子實現文件的傳輸.這種方法有別于ftp協議實現的的文件傳輸方法,利用ftp的方法需要一個專門的服務器和客戶端,無疑于我們要實現的點對點的文件傳輸太為復雜了一些。在這里,我們實現一個輕量級的方法來實現點對點的文件傳輸,這樣就達到了intenet上任何兩個計算機的文件共享。
在兩臺計算機傳輸文件之前,必需得先有一臺計算機建立套節子連接并綁定一個固定得端口,并在這個端口偵聽另外一臺計算機的連接請求。
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 )
{
clientsock = socket.accept();
if ( clientsock.connected )
{
thread tc = new thread(new threadstart(listenclient));
tc.start();
}
}
下面的代碼展示了listenclient方法是如何處理另外一臺計算機發送過來的請求。首先并對發送過來的請求字符串作出判斷,看看是何種請求,然后決定相應的處理方法。
void listenclient()
{
socket sock = clientsock ;
try
{
while ( sock != null )
{
byte[] recs = new byte[32767];
int rcount = sock.receive(recs,recs.length,0) ;
string message = system.text.encoding.ascii.getstring(recs) ;
//對message作出處理,解析處請求字符和參數存儲在cmdlist 中
execmd=cmdlist[0];
sender = null ;
sender = new byte[32767];
string parm1 = "";
//目錄列舉
if ( execmd == "listing" )
{
listfiles(message);
continue ;
}
//文件傳輸
if ( execmd == "getok" )
{
cmd = "beginsend " + filepath + " " + filesize ;
sender = new byte[1024];
sender = encoding.ascii.getbytes(cmd);
sock.send(sender, sender.length , 0 );
//轉到文件下載處理
downloadingfile(sock);
continue ;
}
}
}
catch(exception se)
{
string s = se.message;
console.writeline(s);
}
}
至此,基本的工作已經完成了,下面我們看看如何處理文件傳輸的。
while(rdby < total && nfs.canwrite)
{
//從要傳輸的文件讀取指定長度的數據
len =fin.read(buffed,0,buffed.length) ;
//將讀取的數據發送到對應的計算機
nfs.write(buffed, 0,len);
//增加已經發送的長度
rdby=rdby+len ;
}
從上面的代碼可以看出是完成文件轉換成filestream 流,然后通過networkstream綁定對應的套節子,最后調用他的write方法發送到對應的計算機。
我們再看看接受端是如何接受傳輸過來的流,并且轉換成文件的:
networkstream nfs = new networkstream(sock) ;
try
{
//一直循環直到指定的文件長度
while(rby < size)
{
byte[] buffer = new byte[1024] ;
//讀取發送過來的文件流
int i = nfs.read(buffer,0,buffer.length) ;
fout.write(buffer,0,(int)i) ;
rby=rby+i ;
}
fout.close() ;
從上面可以看出接受與發送恰好是互為相反的過程,非常簡單。
//取得預保存的文件名
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
{
//嘗試連接
socket.connect(hostep);
}
catch(exception se)
{
leixuncms.common.messagebox.show(this.page,"連接錯誤"+se.message);
}
新聞熱點
疑難解答