(圖1)
C#語言由於其對網絡功能良好的支持,特別是內置地支持TCPListener和TCPClIEnt這二個類,使得利用它開發P2P應用程序變得非常容易。下面就是一個使用C#開發的P2P應用的例子:
public MyTcpListener(int port) : base(port)
{
}
public void StopMe()
{
if ( this.Server != null )
{
this.Server.Close();
}
}
}
public class Transfer
{
MyTcpListener tcpl;
public Transfer()
{
OptionsLoader ol = new OptionsLoader();
int port = 8081;
if (ol.Port > 0)
{
port = ol.Port;
}
else
{
port = 8081;
}
this.tcpl = new MyTcpListener(port);
}
public void TransferShutdown()
{
tcpl.StopMe();
}
public void ListenForPeers()
{
try
{
Encoding ASCII = Encoding.ASCII;
tcpl.Start();
while (true)
{
// 在有連接之前,Accept將處於阻塞狀態
Socket s = tcpl.AcceptSocket();
NetworkStream DataStream = new NetworkStream(s);
String filename;
Byte[] Buffer = new Byte[256];
DataStream.Read(Buffer, 0, 256);
filename = Encoding.ASCII.GetString(Buffer);
StringBuilder sbFileName = new StringBuilder(filename);
StringBuilder sbFileName2 = sbFileName.Replace("\", "\\");
FileStream fs = new FileStream(sbFileName2.ToString(), FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
byte[] bytes = new byte[1024];
int read;
while((read = reader.Read(bytes, 0, bytes.Length)) != 0)
{
DataStream.Write(bytes, 0, read);
}
reader.Close();
DataStream.Flush();
DataStream.Close();
}
}
catch(SocketException ex)
{
MessageBox.Show(ex.ToString());
}
}
public void DownloadToClIEnt(String server, string remotefilename, string localfilename)
{
try
{
TcpClient tcpc = new TcpClIEnt();
Byte[] read = new Byte[1024];
OptionsLoader ol = new OptionsLoader();
int port = 0;
if (ol.Port > 0)
{
port = ol.Port;
}
else
{
// 缺省的端口號,可以設置為使用的端口號
port = 8081;
}
// 嘗試與服務器連接
IPHostEntry IPHost = Dns.Resolve(server);
string []aliases = IPHost.Aliases;
IPAddress[] addr = IPHost.AddressList;
IPEndPoint ep = new IPEndPoint(addr[0], port);
tcpc.Connect(ep);
// 獲得流對象
Stream s = tcpc.GetStream();
Byte[] b = Encoding.ASCII.GetBytes(remotefilename.ToCharArray());
s.Write( b, 0, b.Length );
int bytes;
FileStream fs = new FileStream(localfilename, FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs);
// 讀取流對象,並將其轉換為ASCII碼
while( (bytes = s.Read(read, 0, read.Length)) != 0)
{
w.Write(read, 0, bytes);
read = new Byte[1024];
}
tcpc.Close();
w.Close();
fs.Close();
}
catch(Exception ex)
{
throw new Exception(ex.ToString());
}
}
}
}