Socket -- UdpClinet
        【摘要】     UdpClient 类使用字节数组保存 UDP 数据文报。使用 Send 方法向网络发送数据,使用 Receive 方法接收传入的数据文报。 
UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报。因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接。但您可以选择使用下面两种方法之一来建立默认远程主机:...
    
    
    
    UdpClient 类使用字节数组保存 UDP 数据文报。使用 Send 方法向网络发送数据,使用 Receive 方法接收传入的数据文报。
UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报。因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接。但您可以选择使用下面两种方法之一来建立默认远程主机:
使用远程主机名和端口号作为参数创建 UdpClient 类的实例。
创建 UdpClient 类的实例,然后调用 Connect 方法。
  
 - 1
 - 2
 - 3
 
可以使用在 UdpClient 中提供的任何一种发送方法将数据发送到远程设备。使用 Receive 方法可以从远程主机接收数据。
UdpClient 方法还允许发送和接收多路广播数据报。使用 JoinMulticastGroup 方法可以将 UdpClient 预订给多路广播组。使用 DropMulticastGroup 方法可以从多路广播组中取消对 UdpClient 的预订。
简例: 
 作为服务端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace udpClient
{ class Program { static void Main(string[] args) { //创建udpClient 绑定Ip跟端口号,, UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355)); Console.WriteLine("创建UdpClient服务端"); while (true) { //接收数据 IPEndPoint point = new IPEndPoint(IPAddress.Any, 0); //通过point确定数据来自哪个ip的端口号,返回值是一个字节数组, byte[] data = udpClient.Receive(ref point); string message = Encoding.UTF8.GetString(data); Console.WriteLine("收到了消息:" + message); } udpClient.Close(); Console.ReadKey(); } }
}
  
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 - 11
 - 12
 - 13
 - 14
 - 15
 - 16
 - 17
 - 18
 - 19
 - 20
 - 21
 - 22
 - 23
 - 24
 - 25
 - 26
 - 27
 - 28
 - 29
 - 30
 - 31
 
作为客户端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace _004_udpClient
{ class Program { static void Main(string[] args) { //创建UdpClient 绑定的端口号 UdpClient udpclient = new UdpClient(); Console.WriteLine("创建UdpClient客户端"); while (true) { string message = Console.ReadLine(); //将字符串转为数组 byte[] data = Encoding.UTF8.GetBytes(message); //发送数据 int length = udpclient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355)); } udpclient.Close(); Console.ReadKey(); } }
}
  
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 - 11
 - 12
 - 13
 - 14
 - 15
 - 16
 - 17
 - 18
 - 19
 - 20
 - 21
 - 22
 - 23
 - 24
 - 25
 - 26
 - 27
 - 28
 - 29
 - 30
 - 31
 

文章来源: czhenya.blog.csdn.net,作者:陈言必行,版权归原作者所有,如需转载,请联系作者。
原文链接:czhenya.blog.csdn.net/article/details/78299276
        【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
            cloudbbs@huaweicloud.com
        
        
        
        
        
        
        - 点赞
 - 收藏
 - 关注作者
 
            
           
评论(0)