p2p协议连接两个局域网 (p2p协议实现源码)

P2P(Peer to Peer)协议是一种节点对等的网络协议。它的主要作用是:

  1. 资源共享:P2P网络中的节点可以直接共享资源,如文件、计算资源等,实现去中心化的资源共享。
  2. 提高扩展性:P2P网络可以实现节点的动态加入和退出,网络规模可以很容易扩展到成千上万的节点。
  3. 增强鲁棒性:P2P网络的去中心化特性,使其不依赖于个别节点,可以抵抗部分节点的失效和攻击,网络性能不易受到影响。
  4. 分布式计算:P2P网络拥有大量节点资源,可以用于分布式计算、区块链等场景。

P2P工作原理:

  1. 建立连接:P2P节点需要先与网络中的其它节点建立连接,以加入P2P网络。
  2. 资源注册:节点将自己拥有的资源在网络中注册,包括资源信息、节点地址等。
  3. 资源查询:节点可以广播查询请求,查找所需要的资源所在节点。或通过资源索引节点查找。
  4. 直接传输:节点与资源所有节点建立直接连接,进行数据或者计算资源的传输与交互。
  5. 资源下线:节点可以选择将不再共享的资源从网络中注销。

p2p协议能修改吗,p2p协议教程

namespace P2PRelease

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

CheckForIllegalCrossThreadCalls = false;

}

int Count = 0;

PeerNameRegistration[] PeerNameRegister = new PeerNameRegistration[50];

List<string> filePathList = new List<string>();

[Obsolete]

private void Form1_Load(object sender, EventArgs e)

{

IPAddress myip = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);

TexBoxLocalIp.Text = myip.ToString();

TexBoxLocalPort.Text = new Random().Next(10000, 15000).ToString();

Thread threadSendFile = new Thread(new ThreadStart(FileSend));

threadSendFile.Start();

}

private void FileSend()

{

while (true)

{

Socket socket = new Socket(AddressFamily.InterNetwork,

SocketType.Stream, ProtocolType.Tcp);

socket.Bind(new IPEndPoint(IPAddress.Any, 8000));

socket.Listen(1);

Socket client=socket.Accept();

byte[] fileNameBuffer = new byte[1024];

int pathLength=client.Receive(fileNameBuffer);

string fileName = Encoding.UTF8.GetString(fileNameBuffer, 0, pathLength);

string path="";

foreach(string name in filePathList)

{

if(fileName==name.Substring(name.LastIndexOf('\\')+1))

{

path = name;

break;

}

}

if (path == "")

{

client.Send(Encoding.UTF8.GetBytes("File not found!"));

client.Shutdown(SocketShutdown.Both);

client.Close();

socket.Close();

}

else

{

FileStream fs = File.OpenRead(path);

byte[] sendSize = Encoding.UTF8.GetBytes(fs.Length.ToString());

client.Send(sendSize);

int sendLength = 0;

byte[] sendData = new byte[1024];

while ((sendLength = fs.Read(sendData,0,sendData.Length)) > 0)

{

client.Send(sendData);

}

client.Shutdown(SocketShutdown.Both);

client.Close();

socket.Close();

}

}

}

private void ButtRegister_Click(object sender, EventArgs e)

{

//if (TexBoxResName.Text == "")

//{

// MessageBox.Show("请填写资源名");

// return;

//}

OpenFileDialog dialog = new OpenFileDialog();

dialog.InitialDirectory = @"d:\";

if (DialogResult.No == dialog.ShowDialog())

{

return;

}

string filePath = dialog.FileName;

filePathList.Add(filePath);

TexBoxResName.Text = filePath.Substring(filePath.LastIndexOf('\\')+1);

PeerName peerName = new PeerName(TexBoxResName.Text, PeerNameType.Unsecured);

PeerNameRegister[Count] = new PeerNameRegistration(peerName, Convert.ToInt32(TexBoxLocalPort.Text));

PeerNameRegister[Count].Comment = peerName.ToString();

PeerNameRegister[Count].Data = Encoding.UTF8.GetBytes(String.Format("{0}", DateTime.Now.ToString()));

PeerNameRegister[Count].Start();

Count++;

ShareList.Items.Add(peerName.ToString());

}

private void ButtRevoke_Click(object sender, EventArgs e)

{

if (Count == 0)

{

MessageBox.Show("没有要撤销的资源。");

return;

}

int index = ShareList.SelectedIndex;

if (index == -1)

{

MessageBox.Show("请选择要撤销的资源!");

return;

}

for(int i = 0; i < Count; i++)

{

if (PeerNameRegister[i].Comment == ShareList.Text.ToString())

{

PeerNameRegister[i].Stop();

ShareList.Items.RemoveAt(index);

break;

}

}

}

private void ButtSearch_Click(object sender, EventArgs e)

{

if (TexBoxSearchName.Text == "")

{

MessageBox.Show("请输入要搜索的资源名字");

return;

}

ViewResultlist.Items.Clear();

PeerName SearchName = new PeerName(TexBoxSearchName.Text, PeerNameType.Unsecured);

PeerNameResolver Resolver = new PeerNameResolver();

PeerNameRecordCollection collection = Resolver.Resolve(SearchName);

foreach(PeerNameRecord record in collection)

{

foreach(IPEndPoint iep in record.EndPointCollection)

{

if (iep.AddressFamily.Equals(AddressFamily.InterNetwork))

{

ListViewItem item = new ListViewItem();

item.SubItems.Add(TexBoxSearchName.Text);

item.SubItems.Add(iep.ToString());

item.SubItems.Add(Encoding.UTF8.GetString(record.Data));

ViewResultlist.Items.Add(item);

}

}

}

}

IPEndPoint remotePoint; string filename; FileStream downFile; SaveFileDialog saveFile;

private void ButtDown_Click(object sender, EventArgs e)

{

if (ViewResultlist.Items.Count == 0)

{

MessageBox.Show("Resource is not found!");

return;

}

ProgressFileDown.Value = 0;

Socket client = new Socket(AddressFamily.InterNetwork,

SocketType.Stream, ProtocolType.Tcp);

ListViewItem item = ViewResultlist.Items[0];

filename = item.SubItems[1].Text.ToString();

string location = item.SubItems[2].Text.ToString();

saveFile = new SaveFileDialog();

saveFile.FileName = filename;

if (DialogResult.No == saveFile.ShowDialog())

{

return;

}

downFile = File.Open(saveFile.FileName, FileMode.OpenOrCreate, FileAccess.Write);

try

{

string ip = location.Substring(0, location.LastIndexOf(':'));

remotePoint = new IPEndPoint(IPAddress.Parse(ip), 8000);

Thread connectThread = new Thread(new ParameterizedThreadStart(ConneceServer));

connectThread.Start(client);

}catch{

MessageBox.Show("*载下**服务器暂时未开启!");

}

}

private void ConneceServer(object obj)

{

Socket client = (Socket)obj;

try { client.Connect(remotePoint); }

catch

{

client.Close();

downFile.Close();

File.Delete(saveFile.FileName);

return;

}

client.Send(Encoding.UTF8.GetBytes(filename));

byte[] sizeData = new byte[1024];

int sizeLeng = client.Receive(sizeData);

string fileSzieStr = Encoding.UTF8.GetString(sizeData, 0, sizeLeng);

long fileSize = Convert.ToInt64(fileSzieStr);

int length = 0;

long receiveLength = 0;

byte[] fileData = new byte[1024];

length = client.Receive(fileData);

while ( length> 0)

{

downFile.Write(fileData, 0, length);

receiveLength += length;

ProgressFileDown.Value = (int)(receiveLength * 1.0 / fileSize * 100);

fileData = new byte[1024];

length = client.Receive(fileData);

}

downFile.Close();

client.Shutdown(SocketShutdown.Both);

client.Close();

}

}

}