UDP不屬於面向連接的通信,在選擇使用協議的時候,選擇UDP必須要謹慎。在網絡質量令人十分不滿意的環境下,UDP協議數據包丟失會比較嚴重。但是由於UDP的特性:它不屬於連接型協議,因而具有資源消耗小,處理速度快的優點,所以通常音頻、視頻和普通數據在傳送時使用UDP較多,因為它們即使偶爾丟失一兩個數據包,也不會對接收結果產生太大影響。比如我們聊天用的ICQ和QQ就是使用的UDP協議。
我們通過UDP進行信息收發的時候,沒有嚴格客戶端和服務端的區別,它不同於UDP,UDP 必須建立可靠連接之后才可以通信,而UDP隨時都可以給指定的ip和端口所對應進程發送消息。UDP發送消息時需要綁定自己IP 和 端口號,接收消息的時候沒有特殊限制,只要有人給自己發送,自己在線,就可以接收。
服務端程序:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; using System.Threading; namespace UDP_Server { class Program { static Socket server; static void Main(string[] args) { server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6001));//綁定端口號和IP Console.WriteLine("服務端已經開啟"); Thread t = new Thread(ReciveMsg);//開啟接收消息線程 t.Start(); Thread t2 = new Thread(sendMsg);//開啟發送消息線程 t2.Start(); } /// <summary> /// 向特定ip的主機的端口發送數據報 /// </summary> static void sendMsg() { EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000); while (true) { string msg = Console.ReadLine(); server.SendTo(Encoding.UTF8.GetBytes(msg), point); } } /// <summary> /// 接收發送給本機ip對應端口號的數據報 /// </summary> static void ReciveMsg() { while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用來保存發送方的ip和端口號 byte[] buffer = new byte[1024]; int length = server.ReceiveFrom(buffer, ref point);//接收數據報 string message = Encoding.UTF8.GetString(buffer,0,length); Console.WriteLine(point.ToString()+ message); } } } }
客戶端程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Threading; namespace UDP_client { class Program { static Socket client; static void Main(string[] args) { client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); client.Bind(new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6000)); Thread t = new Thread(sendMsg); t.Start(); Thread t2 = new Thread(ReciveMsg); t2.Start(); Console.WriteLine("客戶端已經開啟"); } /// <summary> /// 向特定ip的主機的端口發送數據報 /// </summary> static void sendMsg() { EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6001); while(true){ string msg = Console.ReadLine(); client.SendTo(Encoding.UTF8.GetBytes(msg), point); } } /// <summary> /// 接收發送給本機ip對應端口號的數據報 /// </summary> static void ReciveMsg() { while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用來保存發送方的ip和端口號 byte[] buffer = new byte[1024]; int length = client.ReceiveFrom(buffer, ref point);//接收數據報 string message = Encoding.UTF8.GetString(buffer, 0, length); Console.WriteLine(point.ToString() + message); } } } }
http://download.csdn.net/detail/u011484013/9488304
來源:http://blog.csdn.net/u011484013/article/details/51131267