UDP 是User Datagram Protocol的簡稱, 中文名是用戶數據報協議,是OSI(Open System Interconnection,開放式系統互聯) 參考模型中一種無連接的傳輸層協議,提供面向事務的簡單不可靠信息傳送服務。UDP有不提供數據包分組、組裝和不能對數據包進行排序的缺點,也就是說,當報文發送之后,是無法得知其是否安全完整到達的
udp服務端
udp服務端客戶端流程圖
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8090));
EndPoint clientPoint= new IPEndPoint(IPAddress.Any, 0); // 聲明一個空的端口對象,當接受到數據的時候,會將數據發送方的地址賦值到該對象中
byte[] reciveData = new byte[1024];
int dataLength = server.ReceiveFrom(reciveData, ref clientPoint); //接收到連接,會將連接方的地址寫入clientPoint
string reciveMessage = Encoding.UTF8.GetString(reciveData, 0, dataLength);
Console.WriteLine(reciveMessage);
server.Close();
Console.ReadKey();
}
udp客戶端
static void Main(string[] args)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string userMessage = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(userMessage);
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 8090);
clientSocket.SendTo(data, serverPoint);
Console.ReadKey();
}