使用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();      //发送方端口
        }
}

 


文章出处:http://www.diybl.com/course/4_webprogram/asp.net/asp_netshl/2008513/115886.html

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