它仅在我在发送和接收中使用相同端口(9050或其他)时才有效,那么如何在同一台计算机上同时在多个客户端中接收多播?如果我在多个客户端中使用相同的端口,则会多次使用同一端口的套接字错误
http://codeidol.com/csharp/csharp-network/IP-Multicasting/Csharp-IP-Multicast-Support/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UdpClientMultiSend
{
public static void Main()
{
UdpClient sock = new UdpClient();
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
sock.Send(data, data.Length, iep);
sock.Close();
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UdpClientMultiRecv
{
public static void Main()
{
UdpClient sock = new UdpClient(9050);
Console.WriteLine("Ready to receive…");
sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
byte[] data = sock.Receive(ref iep);
string stringData = Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine("received: {0} from: {1}", stringData, iep.ToString());
sock.Close();
}
}
答案 0 :(得分:3)
看到这篇文章的答案: Connecting two UDP clients to one port (Send and Receive)
您必须在绑定前设置套接字选项。
static void Main(string[] args)
{
IPEndPoint localpt = new IPEndPoint(IPAddress.Any, 6000);
UdpClient udpServer = new UdpClient();
udpServer.Client.SetSocketOption(
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localpt);
UdpClient udpServer2 = new UdpClient();
udpServer2.Client.SetSocketOption(
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer2.Client.Bind(localpt); // <<---------- No Exception here
Console.WriteLine("Finished.");
Console.ReadLine();
}
答案 1 :(得分:0)
在udpClient类上将ExclusiveAddressUse属性设置为false。
有关如何使用它的详细说明,请参阅documentation。