C#中應用UDP通訊實例。本站提示廣大學習愛好者:(C#中應用UDP通訊實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中應用UDP通訊實例正文
收集通訊協定中的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();//封閉銜接 } }
法式終究運轉後果以下: