c# 實現簡單udp數據的發送和接收


服務端代碼

static void Main(string[] args)
{
  UdpClient client = null;
  string receiveString = null;
  byte[] receiveData = null;
  //實例化一個遠程端點,IP和端口可以隨意指定,等調用client.Receive(ref remotePoint)時會將該端點改成真正發送端端點
  IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);

  while (true)
  {
    client = new UdpClient(11000);
    receiveData = client.Receive(ref remotePoint);//接收數據
    receiveString = Encoding.Default.GetString(receiveData);
    Console.WriteLine(receiveString);
    client.Close();//關閉連接
  }
}

 

客戶端代碼

static void Main(string[] args)
{
  string sendString = null;//要發送的字符串
  byte[] sendData = null;//要發送的字節數組
  UdpClient client = null;

  IPAddress remoteIP = IPAddress.Parse("123.45.6.7"); //假設發送給這個IP
  int remotePort = 11000;
  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();//關閉連接
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM