当前位置:编程文档 >> C# >> 使用UDP协议发送和接收数据
首页

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

所属类别:C#
推荐指数:★★☆
文档人气:16
本周人气:6
发布日期:2008-8-2

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

文档说明:

     

相关文档


读取评论列表……