栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#中使用UDP通信实例

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#中使用UDP通信实例

网络通信协议中的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();//关闭连接 
  } 
}

程序最终运行效果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/126225.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号