1. 程式人生 > 其它 >UDP伺服器端和客戶端

UDP伺服器端和客戶端

  UDPServer:

Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress iPAddress = new IPAddress(new byte[] { 172, 16, 160, 50 });
IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 1122);

udpServer.Bind(iPEndPoint); //udp有繫結,但是沒有連線、監聽.....

IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);//IPAddress.Any:任意的IP地址, 0:埠號也任意
EndPoint ep = (EndPoint)ipep;

byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data ,ref ep);
           
Console.WriteLine("接收到資料:" + Encoding.UTF8.GetString(data, 0, length));

TCP建立連線時會返回一個插口(socket)Socket client = tcpServer.Accept();

而UDP只接收資料包,不建立連線。

  UDPClient:

Socket udpclient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
byte[] data = Encoding.UTF8.GetBytes("udp客戶端上線了");

IPAddress ipaddress = new IPAddress(new byte[] { 172, 16, 160, 50 });
//ip+port 終端
IPEndPoint iPEndPoint = new IPEndPoint(ipaddress, 1122);

udpclient.SendTo(data,iPEndPoint);

沒有嚴格意義上的客戶端和伺服器端,雙方都可以呼叫SendTo()傳送訊息,呼叫ReceiveFrom()接收訊息。

TCP通訊需建立連線,資料可靠性,傳送較慢。

UDP通訊給個地址就可以傳送資料和接收資料,速度較快。