使用UDP協議發送和接收數據

首選引用以下兩個:
using System.Net;
using System.Net.Sockets;

//獲取機機IP地址:
IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());
IPAddress myself = ihe.AddressList[0];
//發送消息
UdpClient udpClient = new UdpClient(Ip地址,端口);
Byte[] sendBytes = Encoding.UTF8.GetBytes("信息內容" );   
udpClient.Send(sendBytes, sendBytes.Length);        //發送消息
//偵聽消息
UdpClient receivingUdpClient = new UdpClient(偵聽端口);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
 while (true)         //循環掃描
{
       try
       {
            Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);    //獲取接受到的信息,傳的時候是以Byte[]來傳的,所以接受時也要用Byte
              string stripaddress = RemoteIpEndPoint.Address.ToString();    //發送方IP地址
               string strPort=RemoteIpEndPoint.Port.ToString();      //發送方端口
        }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章