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());
}
}
}
}
……