/// <summary>
///A程序发送数据
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("192.168.1.100"); //假设发送给这个IP
int remotePort = 8021;///端口号
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点
while (true)
{
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
client.Close();//关闭连接
}
}
/// <summary>
/// B程序接收数据
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
///这里是不需要知道发送者的IP,只需要端口号,因为这里是接收
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
client = new UdpClient(2003);
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//关闭连接
}
}