这些天由于有个p2p的项目,于是恶补了一下自己在网络编程方面的知识,下面一个程序是我在这过程中的一个很小的程序,想看看这个udp协议是不是适合做p2p。如果哪位朋友是做p2p的,请不吝赐教!加小弟的QQ:422158979,小弟先谢谢了!
下面将我自己的代码贴出来,希望各位指正!
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPChat
{
class Program
{
private static IPAddress remoteAddress;
private static int remotePort;
private static int localPort;
[STAThread ]
static void Main(string[] args)
{
try
{
Console.Write("Enter Local Port-----");
localPort = Convert.ToInt16(Console.ReadLine());
Console.Write("Enter Remote Port----");
remotePort = Convert.ToInt16(Console.ReadLine());
Console.Write("Enter Remote IP address----");
remoteAddress = IPAddress.Parse(Console.ReadLine());
Thread tRec = new Thread(new ThreadStart(Receiver));
tRec.Start();
while (true)
{
Send(Console.ReadLine());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString ());
}
}
private static void Send(string p)
{
UdpClient sender = new UdpClient();
IPEndPoint endPoint = new IPEndPoint(remoteAddress ,remotePort );
try
{
byte[] bytes = Encoding.ASCII.GetBytes(p);
sender.Send(bytes, bytes.Length, endPoint);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
sender.Close();
}
}
public static void Receiver()
{
UdpClient receivingUdpClient = new UdpClient(localPort);
IPEndPoint remoteiendpoint = null;
try
{
Console.WriteLine("--------Ready For Chat!!!!!!!!------------");
while (true)
{
byte[] receivedBytes = receivingUdpClient.Receive(ref remoteiendpoint);
string returnData = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("-" + returnData.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString ());
}
}
}
}
由于是一个聊天程序,因此需要打开两个窗口。试验时候将A窗口的Local端口号设置为2002,Remote端口号设置为2001。B窗口正好与A端口号相反。这样就可以正常运行了!