P2P资源注册与发现程序开发

作者:追风剑情 发布于:2025-9-3 22:53 分类:C#

2222.png

using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Net.PeerToPeer;
using System.Text;
using System.Linq;

namespace TestP2P
{
    /// <summary>
    /// 在运行中输入 services.msc 打开服务窗口,确保以下服务处于运行状态: 
    /// (1) "PNRP Machine Name Publication Service"
    /// (2) "Peer Networking Grouping"
    /// 测试时需要运行两个端
    /// </summary>
    public partial class FormP2PResDiscvery : Form
    {
        //分享的资源数
        int Count = 0;
        //云
        Cloud cloud;
        //最多能注册50个资源
        PeerNameRegistration[] PeerNameRegister = new PeerNameRegistration[50];

        public FormP2PResDiscvery()
        {
            InitializeComponent();
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void FormP2PResDiscvery_Load(object sender, EventArgs e)
        {
            long address = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address;
            //获取本机IP地址
            IPAddress myip = new IPAddress(address);
            //显示IP地址
            TextBoxLocalIP.Text = myip.ToString();
            //设置端口号,随机产生
            int port = new Random().Next(10000, 15000);
            //显示使用的端口号
            TextBoxLocalPort.Text = port.ToString();

            //尝试使用 LinkLocal 云而不是 Global
            cloud = Cloud.GetAvailableClouds().FirstOrDefault(c => c.Scope == PnrpScope.LinkLocal) ?? Cloud.AllLinkLocal;
            //显示云名称
            labelCloud.Text = cloud.Name;
        }

        //注册按钮
        private void ButtonRegister_Click(object sender, EventArgs e)
        {
            //如果未填写资源名
            if (string.IsNullOrEmpty(TextBoxResName.Text))
            {
                MessageBox.Show("请填写资源名");
                return;
            }

            //端口
            int port = Convert.ToInt32(TextBoxLocalPort.Text);
            //将资源名注册到云中
            //创建非安全类型的PeerName对象
            PeerName peerName = new PeerName(TextBoxResName.Text, PeerNameType.Unsecured);
            //用指定的名称和端口号初始化PeerNameRegistration类的新实例
            PeerNameRegister[Count] = new PeerNameRegistration(peerName, port, cloud);
            PeerNameRegister[Count].Comment = peerName.ToString();
            //注意:安全名称以 "0." 开头,非安全以 "1." 开头
            Console.WriteLine("注册资源: {0}", peerName.ToString());
            PeerNameRegister[Count].Data = Encoding.UTF8.GetBytes(String.Format("{0}", DateTime.Now.ToString()));
            //因为IPv4不支持全局云,IPv6才支持全局云,所以默认使用默认云,不需要进行设置
            //完成注册
            PeerNameRegister[Count].Start();
            Count++;
            //向分享列表中添加分享的资源
            ShareList.Items.Add(peerName.ToString());
        }

        //撤销按钮
        private void ButtonRevoke_Click(object sender, EventArgs e)
        {
            //没有分享资源
            if (Count == 0) {
                return;
            }
            //没有选中要撤销的资源
            int index = ShareList.SelectedIndex;
            if (index == -1)
            {
                MessageBox.Show("请选择要撤销的资源!");
                return;
            }
            //撤销分享的资源
            for (int i = 0; i < Count; i++)
            {
                if (PeerNameRegister[i].Comment == ShareList.Text)
                {
                    PeerNameRegister[i].Stop();
                    ShareList.Items.RemoveAt(index);
                    break;
                }
            }
        }

        //搜索按钮
        private void ButtonSearch_Click(object sender, EventArgs e)
        {
            //搜索资源名为空
            if (string.IsNullOrEmpty(TextBoxSearchName.Text)) 
            {
                MessageBox.Show("请输入搜索的资源名字");
                return;
            }
            //清空ResultList
            ViewResultList.Items.Clear();
            PeerName searchName = new PeerName(TextBoxSearchName.Text, PeerNameType.Unsecured);
            Console.WriteLine("搜索资源: {0}", searchName.ToString());
            PeerNameResolver resolver = new PeerNameResolver();
            //获取PeerNameRecord集合
            PeerNameRecordCollection collection = resolver.Resolve(searchName, cloud);
            //遍历PeerNameRecord集合
            foreach (PeerNameRecord record in collection)
            {
                foreach (IPEndPoint iep in record.EndPointCollection)
                {
                    if (!iep.AddressFamily.Equals(AddressFamily.InterNetwork))
                        continue;
                    string value1 = iep.ToString();
                    string value2 = Encoding.UTF8.GetString(record.Data);
                    string[] values = new string[] { value1, value2 };
                    ListViewItem item = new ListViewItem(values);
                    ViewResultList.Items.Add(item);
                }
            }
        }
    }
}

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号