標籤:byte buffer utf8 logs 非同步 udp color client add
首先是發送端:
/// <summary>/// 發送UDP訊息/// </summary>/// <param name="msg">訊息內容</param>void Send(string msg){ UdpClient udpClient = new UdpClient(); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Broadcast, 10249); byte[] buffer = Encoding.UTF8.GetBytes(msg); udpClient.Send(buffer, buffer.Length, ipEndPoint);}
然後是接收端:
static void Main(){ UdpClient udpServer = new UdpClient(10249); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 10249); 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來做!
C# UDP廣播訊息