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

本文提供两个C#范例,展示了如何使用UdpClient类在端口11000上发送和接收UDP资料包到多点传送位址群组224.168.100.2。发送端程式将命令列参数作为消息发送,接收端则监听并打印接收到的消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    下列范例使用 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; 

}  
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值