你必須結合之前套接字選項設置。
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();
}
你得到什麼異常? – 2012-02-02 21:14:47
@ M.Babcock 我得到的異常消息是: 「嘗試以訪問權限禁止的方式訪問套接字」 – brooc 2012-02-02 21:24:43
嘗試綁定時,您的udpServer實例是否會拋出相同的異常? – 2012-02-02 21:33:48