首页 > Windows开发 > 详细

c# 实现简单udp数据的发送和接收

时间:2017-01-05 10:55:39      阅读:268      评论:0      收藏:0      [点我收藏+]

服务端代码

static void Main(string[] args)
{
  UdpClient client = null;
  string receiveString = null;
  byte[] receiveData = null;
  //实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点
  IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);

  while (true)
  {
    client = new UdpClient(11000);
    receiveData = client.Receive(ref remotePoint);//接收数据
    receiveString = Encoding.Default.GetString(receiveData);
    Console.WriteLine(receiveString);
    client.Close();//关闭连接
  }
}

 

客户端代码

static void Main(string[] args)
{
  string sendString = null;//要发送的字符串
  byte[] sendData = null;//要发送的字节数组
  UdpClient client = null;

  IPAddress remoteIP = IPAddress.Parse("123.45.6.7"); //假设发送给这个IP
  int remotePort = 11000;
  IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点

  while (true)
  {
    sendString = Console.ReadLine();
    sendData = Encoding.Default.GetBytes(sendString);

    client = new UdpClient();
    client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
    client.Close();//关闭连接
  }
}

技术分享

 

c# 实现简单udp数据的发送和接收

原文:http://www.cnblogs.com/longzhankunlun/p/6251436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!