我尝试了this question的建议,但收效甚微。
拜托。。。任何帮助都将不胜感激!
这是我的代码:
static void Main(string[] args)
{
IPEndPoint localpt = new IPEndPoint(IPAddress.Any, 6000);
UdpClient udpServer = new UdpClient(localpt);
udpServer.Client.SetSocketOption(
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
UdpClient udpServer2 = new UdpClient();
udpServer2.Client.SetSocketOption(
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer2.Client.Bind(localpt); // <<---------- Exception here
}
最佳答案
绑定之前必须设置套接字选项。
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();
}
或更具说明性的例子:
static void Main(string[] args)
{
IPEndPoint localpt = new IPEndPoint(IPAddress.Loopback, 6000);
ThreadPool.QueueUserWorkItem(delegate
{
UdpClient udpServer = new UdpClient();
udpServer.ExclusiveAddressUse = false;
udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localpt);
IPEndPoint inEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Listening on " + localpt + ".");
byte[] buffer = udpServer.Receive(ref inEndPoint);
Console.WriteLine("Receive from " + inEndPoint + " " + Encoding.ASCII.GetString(buffer) + ".");
});
Thread.Sleep(1000);
UdpClient udpServer2 = new UdpClient();
udpServer2.ExclusiveAddressUse = false;
udpServer2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer2.Client.Bind(localpt);
udpServer2.Send(new byte[] { 0x41 }, 1, localpt);
Console.Read();
}
关于c# - 将两个UDP客户端连接到一个端口(发送和接收),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9120050/