網絡通信協議中的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();//關閉連接 } }
程序最終運行效果如下:
新聞熱點
疑難解答