C# UDP 通信

public class UDPHelper
{

 public UDPHelper(string sendiP, int sendPort, string localIP, int localPort)
 {
     point = new IPEndPoint(IPAddress.Parse(localIP), Convert.ToInt32(localPort));
     udpClient = new UdpClient();
     udpClient.Client.Bind(point);
     SendPoint = new IPEndPoint(IPAddress.Parse(sendiP), Convert.ToInt32(sendPort));
 }


 public IPEndPoint SendPoint;

 public IPEndPoint point;

 public UdpClient udpClient;

 public void SendMsg(string msg)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(msg);
     udpClient.Send(buffer, buffer.Length, SendPoint);
 }

 public void ReceiveMsg()
 {
     while (true)
     {
         byte[] data = udpClient.Receive(ref point);
         string message = Encoding.Default.GetString(data);
     }
 }

}

posted @ 2025-04-15 17:14  王工王工  阅读(29)  评论(0)    收藏  举报