C#中使用UDP通信的示例

Tallulah ·
更新时间:2024-09-20
· 598 次阅读

网络通信协议中的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通信的示例的详细内容,更多关于c# udp通信的资料请关注软件开发网其它相关文章!

您可能感兴趣的文章:C#判断一个图像是否是透明的GIF图的方法.net c# gif动画如何添加图片水印实现思路及代码c# 获取照片的经纬度和时间的示例代码大白话讲解C# 中的委托C#中Write()和WriteLine()的区别分析c# 动态构建LINQ查询表达式详解c# 协变和逆变c# 播放声音的四种方法C#实现窗体抖动的两种方法c# 制作gif的四种方法



示例 C# udp

需要 登录 后方可回复, 如果你还没有账号请 注册新账号