使用UDP协议发送和接收数据

来源:互联网 发布:app软件销售员好做吗 编辑:程序博客网 时间:2024/04/29 11:03

首选引用以下两个:
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();      //发送方端口
        }
}

 

原创粉丝点击