美文网首页
C#UDP的多路广播组的发送和接收

C#UDP的多路广播组的发送和接收

作者: 久百一 | 来源:发表于2020-10-21 00:27 被阅读0次

    下列范例使用 UdpClient,在通讯端口11000传送UDP 资料包至多点传送位址群组 224.268.100.2。它传送命令列上指定的信息字串。

    [C#] 
    using System; 
    using System.Net; 
    using System.Net.Sockets; 
    using System.Text; 
    public class UDPMulticastSender { 
    
    private static IPAddress GroupAddress = 
    IPAddress.Parse("224.168.100.2"); 
    private static int GroupPort = 11000; 
    
    private static void Send( String message) { 
    UdpClient sender = new UdpClient(); 
    IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort); 
    
    try { 
    Console.WriteLine("Sending datagram : {0}", message); 
    byte[] bytes = Encoding.ASCII.GetBytes(message); 
    
    sender.Send(bytes, bytes.Length, groupEP); 
    
    sender.Close(); 
    
    } catch (Exception e) { 
    Console.WriteLine(e.ToString()); 
    } 
    
    } 
    
    public static int Main(String[] args) { 
    Send(args[0]); 
    
    return 0; 
    } 
    } 
    

    下列范例使用 UdpClient,在通讯端口 11000 监听广播到多点传送位址群组 224.168.100.2 的 UDP 资料包。它接收信息字串,并將信息写入主控台 (Console)。

    [C#] 
    using System; 
    using System.Net; 
    using System.Net.Sockets; 
    using System.Text; 
    public class UDPMulticastListener { 
    
    private static readonly IPAddress GroupAddress = 
    IPAddress.Parse("224.168.100.2"); 
    private const int GroupPort = 11000; 
    
    private static void StartListener() { 
    bool done = false; 
    
    UdpClient listener = new UdpClient(); 
    IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort); 
    
    try { 
    listener.JoinMulticastGroup(GroupAddress); 
    listener.Connect(groupEP); 
    
    while (!done) { 
    Console.WriteLine("Waiting for broadcast"); 
    byte[] bytes = listener.Receive( ref groupEP); 
    
    Console.WriteLine("Received broadcast from {0} :/n {1}/n", 
    groupEP.ToString(), 
    Encoding.ASCII.GetString(bytes,0,bytes.Length)); 
    } 
    
    listener.Close(); 
    
    } catch (Exception e) { 
    Console.WriteLine(e.ToString()); 
    } 
    
    } 
    
    public static int Main(String[] args) { 
    StartListener(); 
    
    return 0; 
    } 
    }  
    

    相关文章

      网友评论

          本文标题:C#UDP的多路广播组的发送和接收

          本文链接:https://www.haomeiwen.com/subject/xjzjmktx.html