C#教程之C#中使用UDP通訊實例

若是須要查看更多文章,請微信搜索公衆號 csharp編程大全,須要進C#交流羣羣請加微信z438679770,備註進羣, 我邀請你進羣! ! !編程

網絡通訊協議中的UDP通訊是無鏈接通訊,客戶端在發送數據前無需與服務器端創建鏈接,即便服務器端不在線也能夠發送,可是不能保證服務器端能夠收到數據。本文實例即爲基於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("127.0.0.1");
  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();//關閉鏈接
  }

  

相關文章
相關標籤/搜索