首先是发送端:
/// <summary>
/// 发送UDP消息
/// </summary>
/// <param name="msg">消息内容</param>
void Send(string msg)
{
UdpClient udpClient = new UdpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Broadcast, ); byte[] buffer = Encoding.UTF8.GetBytes(msg);
udpClient.Send(buffer, buffer.Length, ipEndPoint);
}
然后是接收端:
static void Main()
{
UdpClient udpServer = new UdpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, ); udpServer.BeginReceive(Received, udpServer);
}
/// <summary>
/// 异步接收UDP数据
/// </summary>
/// <param name="iar"></param>
void Received(IAsyncResult iar)
{
udpServer = iar.AsyncState as UdpClient;
byte[] buffer = udpServer.EndReceive(iar, ref ipEndPoint);
//将获取的byte[]数据转换成字符串
string m = Encoding.UTF8.GetString(buffer).Trim();
Console.WriteLine("Receive:{0}",m);
//继续异步接收数据
udpServer.BeginReceive(Received, udpServer);
}
接收端采用了异步执行的方式,当然也可以用Thread来做!