首页 > 编程开发 > Objective-C编程 >
-
c# udp的多路广播组的发送和接收
下列范例使用 UdpClient,在通讯端口11000传送UDP 资料包至多点传送位址群组 224.268.100.2。它传送命令列上指定的信息字串。
[C#]
usingSystem;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
publicclassUDPMulticastSender{
privatestaticIPAddressGroupAddress=
IPAddress.Parse("224.168.100.2");
privatestaticintGroupPort=11000;
privatestaticvoidSend(Stringmessage){
UdpClientsender=newUdpClient();
IPEndPointgroupEP=newIPEndPoint(GroupAddress,GroupPort);
try{
Console.WriteLine("Sendingdatagram:{0}",message);
byte[]bytes=Encoding.ASCII.GetBytes(message);
sender.Send(bytes,bytes.Length,groupEP);
sender.Close();
}catch(Exceptione){
Console.WriteLine(e.ToString());
}
}
publicstaticintMain(String[]args){
Send(args[0]);
return0;
}
}
下列范例使用 UdpClient,在通讯端口 11000 监听广播到多点传送位址群组 224.168.100.2 的 UDP 资料包。它接收信息字串,并將信息写入主控台 (Console)。
[C#]
usingSystem;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
publicclassUDPMulticastListener{
privatestaticreadonlyIPAddressGroupAddress=
IPAddress.Parse("224.168.100.2");
privateconstintGroupPort=11000;
privatestaticvoidStartListener(){
booldone=false;
UdpClientlistener=newUdpClient();
IPEndPointgroupEP=newIPEndPoint(GroupAddress,GroupPort);
try{
listener.JoinMulticastGroup(GroupAddress);
listener.Connect(groupEP);
while(!done){
Console.WriteLine("Waitingforbroadcast");
byte[]bytes=listener.Receive(refgroupEP);
Console.WriteLine("Receivedbroadcastfrom{0}:n{1}n",
groupEP.ToString(),
Encoding.ASCII.GetString(bytes,0,bytes.Length));
}
listener.Close();
}catch(Exceptione){
Console.WriteLine(e.ToString());
}
}
publicstaticintMain(String[]args){
StartListener();
return0;
}
}