作者:Ctrliman 链接:https://www.cnblogs.com/henusfs/archive/2009/06/18/UDP.html
作者:任家 链接:http://blog.sina.com.cn/s/blog_4fcd1ea301014z5l.html
解决方案1
用2个UDP连接,一个用来收,一个用来发
解决方案2
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));/*解决发送时导致接收出现异常:远程主机强迫关闭了一个现有的连接参考:https://www.cnblogs.com/henusfs/archive/2009/06/18/UDP.html*/uint IOC_IN = 0x80000000;uint IOC_VENDOR = 0x18000000;uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;client.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, new byte[4]);
症状
使用UdpClient异步接收时,出现了”远程主机强迫关闭了一个现有的连接”的错误.
重现条件
- 使用UdpClient异步接收
- 发送时对方没有接收
- UDP收和发为同一个
重现代码
static void Main(string[] args){UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));client.BeginReceive(ReceiveData, client);Console.ReadKey();byte[] bytes = Encoding.UTF8.GetBytes("对称加密:是采用单钥密码系统的加密方法,使用同一密钥对信息进行加密和解密的加密方法。");client.Send(bytes, bytes.Length, new IPEndPoint(IPAddress.Loopback, 29129));Console.ReadKey();}public static void ReceiveData(IAsyncResult ar){IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 29129);UdpClient udpClient = ar.AsyncState as UdpClient;byte[] bs = udpClient.EndReceive(ar, ref endPoint);Console.WriteLine(Encoding.UTF8.GetString(bs));udpClient.BeginReceive(ReceiveData, udpClient);}
当运行到 client.Send 发送方法时,接收就出现了”远程主机强迫关闭了一个现有的连接”的错误
方案1修复后代码
static void Main(string[] args){UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));client.BeginReceive(ReceiveData, client);Console.ReadKey();UdpClient udpclient = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));byte[] bytes = Encoding.UTF8.GetBytes("对称加密:是采用单钥密码系统的加密方法,使用同一密钥对信息进行加密和解密的加密方法。");udpclient.Send(bytes, bytes.Length, new IPEndPoint(IPAddress.Loopback, 29129));Console.ReadKey();}public static void ReceiveData(IAsyncResult ar){IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 29129);UdpClient udpClient = ar.AsyncState as UdpClient;byte[] bs = udpClient.EndReceive(ar, ref endPoint);Console.WriteLine(Encoding.UTF8.GetString(bs));udpClient.BeginReceive(ReceiveData, udpClient);}
方案2修复后代码
static void Main(string[] args){UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));uint IOC_IN = 0x80000000;uint IOC_VENDOR = 0x18000000;uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;client.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, new byte[4]);client.BeginReceive(ReceiveData, client);Console.ReadKey();byte[] bytes = Encoding.UTF8.GetBytes("对称加密:是采用单钥密码系统的加密方法,使用同一密钥对信息进行加密和解密的加密方法。");client.Send(bytes, bytes.Length, new IPEndPoint(IPAddress.Loopback, 29129));Console.ReadKey();}public static void ReceiveData(IAsyncResult ar){IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 29129);UdpClient udpClient = ar.AsyncState as UdpClient;byte[] bs = udpClient.EndReceive(ar, ref endPoint);Console.WriteLine(Encoding.UTF8.GetString(bs));udpClient.BeginReceive(ReceiveData, udpClient);}
