C#PeerToPeer(对等网络P2P)实例

在 .NET Framework 3.5以上的.Net框架, System.Net.dll 程序集中添加了System.Net.PeerToPeer 命名空间,它提供了轻松创建对等网络 (P2P) 应用程序所需的核心构建基块。该命名空间是根据典型的 P2P 应用程序的三个阶段而设计的,即: 发现、连接和通信 。发现阶段负责动态定位对等点及其相关的网络位置。连接阶段负责在对等点之间建立网络连接。而通信阶段则负责在对等点之间来回传输数据。
以下实例是基于System.Net.PeerToPeer 的对等网络控制台程序,需要添加System.Net.dll的程序集引用:
using System;
using System.Net.PeerToPeer;
using System.Net;

namespace TestP2P
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建对等名
            PeerName peerName = new PeerName("My Server", PeerNameType.Secured);
       
            //发布对等名
            PeerNameRegistration pnReg = new PeerNameRegistration();
            pnReg.PeerName = peerName;

            pnReg.UseAutoEndPointSelection = true;
            pnReg.Port = 8888;
            //绑定数据
            pnReg.Comment = "其他信息";
            pnReg.Data = System.Text.Encoding.UTF8.GetBytes(
                "12345");
            pnReg.Start();
            Console.WriteLine("Registration of Peer Name: {0} complete.",peerName);

            //解析对等名
            PeerNameResolver resolver = new PeerNameResolver();
            //每个对等点有多个PeerNameRecord
            PeerNameRecordCollection results = resolver.Resolve(peerName);

            // 输出解析后的数据
            Console.WriteLine("Records from resolution of PeerName: {0}",
                peerName);
            Console.WriteLine();

            int count = 1;
            foreach (PeerNameRecord record in results)
            {
                Console.WriteLine("Record #{0} results...", count);

                Console.WriteLine("Comment:");
                if (record.Comment != null)
                {
                    Console.WriteLine(record.Comment);
                }

                Console.WriteLine("Data:");
                if (record.Data != null)
                {
                    Console.WriteLine(
                        System.Text.Encoding.ASCII.GetString(record.Data));
                }

                Console.WriteLine("Endpoints:");
                foreach (IPEndPoint endpoint in record.EndPointCollection)
                {
                    Console.WriteLine("\t Endpoint:{0}", endpoint);
                    Console.WriteLine();
                }

                count++;
            }

            Console.ReadKey();
            pnReg.Stop();
        }
    }
}
在一台电脑上启动多个该实例即可查看结果。

参考文章:

http://www.cnblogs.com/zhili/archive/2012/09/14/P2P_PNPR.html

https://blog.csdn.net/fenggui/article/details/5379572

https://blog.csdn.net/fenggui/article/details/5379564

猜你喜欢

转载自blog.csdn.net/syb1295306116/article/details/80666140
P2P