這篇文章主要介紹了c# socket編程實現udp客戶端,大家參考使用吧
代碼如下: Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName()); //設置服務端終結點 IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001); //創建與服務端連接的套接字,指定網絡類型,數據連接類型和網絡協議 Socket ConnSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); string welcome = "Client Message:Hello!!!"; byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(welcome); //給服務端發送測試消息 ConnSocket.SendTo(data, data.Length, SocketFlags.None, ipe); IPEndPoint server = new IPEndPoint(IPAddress.Any, 0); //服務端終結點 EndPoint Remote = (EndPoint)server; data = new byte[1024]; //對於不存在的IP地址,加入此行代碼後,可以在指定時間內解除阻塞模式限制 //server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100); int recv = ConnSocket.ReceiveFrom(data, ref Remote); //打印從服務端發回的信息 Console.WriteLine("Message received from {0}: ", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); while (true) //可以實時給服務端發送消息 { string input = Console.ReadLine(); if (input == "exit") //中斷連接 { ConnSocket.SendTo(Encoding.ASCII.GetBytes(input), Remote); data = new byte[1024]; recv = ConnSocket.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); break; } else { ConnSocket.SendTo(Encoding.ASCII.GetBytes("Client Message:" + input), Remote); data = new byte[1024]; recv = ConnSocket.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); } } Console.WriteLine("Stopping Client."); ConnSocket.Close();