System.Sockes命名空间了实现 Berkeley 套接字接口。通过这个类,我们可以实现网络计算机之间的消息传输和发送.而在我下面要讨论的这个议题里,我们将讨论的是用套节子实现文件的传输.这种方法有别于FTP协议实现的的文件传输方法,利用ftp的方法需要一个专门的服务器和客户端,无疑于我们要实现的点对点的文件传输太为复杂了一些。在这里,我们实现一个轻量级的方法来实现点对点的文件传输,这样就达到了intenet上任何两个计算机的文件共享。
在两台计算机传输文件之前,必需得先有一台计算机建立套节子连接并绑定一个固定得端口,并在这个端口侦听另外一台计算机的连接请求。
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
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) ;
//messagecmdList
execmdcmdList[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 NetworkStreamwrite
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() ;