UDP中接收和发送数据
Posted yjm8023
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UDP中接收和发送数据相关的知识,希望对你有一定的参考价值。
/// <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();//关闭连接
}
}
以上是关于UDP中接收和发送数据的主要内容,如果未能解决你的问题,请参考以下文章