Oldukça basit bir Eşzamansız UDP dinleyicim var, hizmet olarak ayarlandı ve şimdi bir süredir oldukça iyi çalışıyor ancak son zamanlarda bir SocketException An existing connection was forcibly closed by the remote host
'da çöktü. Şu anda üç sorum var:C# Async UDP dinleyicisi SocketException
- Buna neden oluyor? (UDP soketlerinin bir bağlantısı olduğunu düşünmedim)
- Test amacıyla, nasıl çoğaltıtabilirim?
- İstisnai nasıl temizleyebilirim, böylece her şey çalışmaya devam edecek mi?
private Socket udpSock; private byte[] buffer; public void Starter(){ //Setup the socket and message buffer udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpSock.Bind(new IPEndPoint(IPAddress.Any, 12345)); buffer = new byte[1024]; //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock); } private void DoReceiveFrom(IAsyncResult iar){ try{ //Get the received message. Socket recvSock = (Socket)iar.AsyncState; EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0); int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP); byte[] localMsg = new byte[msgLen]; Array.Copy(buffer, localMsg, msgLen); //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock); //Handle the received message Console.WriteLine("Recieved {0} bytes from {1}:{2}", msgLen, ((IPEndPoint)clientEP).Address, ((IPEndPoint)clientEP).Port); //Do other, more interesting, things with the received message. } catch (ObjectDisposedException){ //expected termination exception on a closed socket. // ...I'm open to suggestions on a better way of doing this. } }
istisna recvSock.EndReceiveFrom() satırında atılıyor:
Kodum aşağıdaki gibi görünür.
Great Man! Merhaba, ICMP mesajları alma ve alındıklarında istisnalar atma konusunda aynı sorun vardı. Kodlama numaranız tarafından çözüldü! – Kevan
@Kyle, sonunda bunu tamamen test etmek için uğraştım! Bu istisnanın gerçek kök nedeniydi. Referans olarak, hem cevabınızı hem de Jim'i kullanarak sona erdim, böylece bir istisna olsa bile dinleyici yeniden başlatılacak. – chezy525
Kırık Bağlantı. Bu cevap, bağlantıyı güncellemek veya bağlantının işaret ettiği bilgileri içerecek şekilde değiştirilmelidir. –