C#异步UDP侦听器SocketException [英] C# Async UDP listener SocketException

查看:110
本文介绍了C#异步UDP侦听器SocketException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的异步UDP侦听器,可以将其设置为服务,并且已经运行了一段时间,但是最近它在SocketException上崩溃了.一个现有的连接被远程主机强行关闭了.我有三个问题:

I have a pretty simple Asynchronous UDP listener, setup as a service, and it's been working quite well for awhile now, but it recently crashed on a SocketException An existing connection was forcibly closed by the remote host. I have three questions:

  1. 是什么原因造成的?(我不认为UDP套接字有连接)
  2. 出于测试目的,如何复制它?
  3. 我该如何干净地处理异常,以便一切都能继续进行?

我的代码如下所示:

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.
    }
}

在recvSock.EndReceiveFrom()行中引发了异常.

The exception is being thrown at the recvSock.EndReceiveFrom() line.

推荐答案

来自

From this forum thread, it seems that the UDP socket is also receiving ICMP messages and throwing exceptions when they are received. Maybe this is great for low level status updates, but I found it annoying.

首先,定义幻数

public const int SIO_UDP_CONNRESET = -1744830452;

然后将底层io控件设置为忽略以下消息:

Then set the low level io control to ignore these messages:

var client = new UdpClient(endpoint);
client.Client.IOControl(
    (IOControlCode)SIO_UDP_CONNRESET, 
    new byte[] { 0, 0, 0, 0 }, 
    null
);

这篇关于C#异步UDP侦听器SocketException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆