码迷,mamicode.com
首页 > Windows程序 > 详细

C#中使用UDP通信实例

时间:2017-11-13 23:24:27      阅读:346      评论:0      收藏:0      [点我收藏+]

标签:null   str   des   手机拍照   orm   发送   ipaddr   端点   read   

网络通信协议中的UDP通信是无连接通信,客户端在发送数据前无需与服务器端建立连接,即使服务器端不在线也可以发送,但是不能保证服务器端可以收到数据。本文实例即为基于C#实现的UDP通信。具体功能代码如下:

服务器端代码如下:

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("127.0.0.1");
  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.paobuke.com/develop/c-develop/pbk23661.html






相关内容

C#中使用UDP通信实例

标签:null   str   des   手机拍照   orm   发送   ipaddr   端点   read   

原文地址:http://www.cnblogs.com/paobuke/p/7828153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!