日期:2014-05-18  浏览次数:21076 次

C# p2p(1)

C# p2p(1)
2012年01月17日
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Net;
  using System.Net.Sockets;
  using System.Net.PeerToPeer; namespace ConsoleApplication4
  {
  class Program
  {
  static string strMYPeername = "myApplicationName";
  static string strAllMyPeername = "";
  static int port;
  static PeerNameRegistration peernameregistration;         static void Main(string[] args)
  {
  registerPeer();
  resoveName("0."+strMYPeername);
  Console.Read();
  }         public static void getPort()
  {
  while (true)
  {
  port = new Random().Next(50000,51000);
  try
  {
  TcpListener listener = new TcpListener(IPAddress.Any, port);
  listener.Start();
  }
  catch
  {
  continue;
  }
  break;
  }
  }             //把PNRP NAME 注册到Cloud中
  public static void registerPeer()
  {
  getPort();//获取要连线的IP&PORT
  PeerName peername = new PeerName(strMYPeername, PeerNameType.Unsecured);
  //用peername创建注册群,然后把peername注册到群中
  peernameregistration = new PeerNameRegistration(peername, port);
  peernameregistration.Comment = "pnrp peer name 的其他描述信息";
  peernameregistration.Data = Encoding.UTF8.GetBytes(string.Format("注册时间{0}",DateTime.Now.ToString()));
  strAllMyPeername = peername.ToString();
  peernameregistration.Start();
  }
  public static void resolverPeer(string myPeername)
  {
  PeerName peerName = new PeerName("0." + myPeername);
  PeerNameResolver resolver = new PeerNameResolver();
  PeerNameRecordCollection pmrcs = resolver.Resolve(peerName);
  foreach (PeerNameRecord pmrc in pmrcs)
  {
  foreach (IPEndPoint endpoint in pmrc.EndPointCollection)
  {
  Console.WriteLine(endpoint);
  }
  }
  }
  ///解析对等名称
  public static void resoveName(string strPeerName)
  {
  PeerName mypeer = new PeerName(strPeerName);
  PeerNameResolver myRes = new PeerNameResolver();
  PeerNameRecordCollection recColl = myRes.Resolve(mypeer);
  foreach (var record in recColl)
  {
  foreach (var endp in record.EndPointCollection)
  {
  if (endp.AddressFamily.Equals(AddressFamily.InterNetw ork))
  {
  Console.WriteLine(record.PeerName.ToString());
  Console.WriteLine(endp.ToString());
  Console.WriteLine(Encoding.UTF8.GetString(record.D ata));
  Console.WriteLine(record.PeerName.PeerHostName);
  }
  }
  }
  }
  }
  }