c#,udpClient.Receive,远程主机强行关闭现有连接

时间:2018-03-28 03:36:34

标签: c# udpclient

好的,我有一个程序可以从数据表中查询游戏服务器并将它们添加到列表视图中。

如果数据表中的某个服务器脱机,我会收到此错误:

An existing connection was forcibly closed by the remote host

抛出此异常的特定代码行是:

Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);

我查询服务器的方法:

private void QueryServer(IPAddress IP, int Port)
{
    udpClient.Connect(IP, Port);

    Byte[] sendBytes = Encoding.ASCII.GetBytes("\\100 * 1024\\");

    udpClient.Send(sendBytes, sendBytes.Length);

    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IP, Port);

    Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);

    string returnData = Encoding.ASCII.GetString(receiveBytes);

    if (returnData == "")
    {
        return;
    }
    else
    {
        ProcessPacket(receiveBytes, receiveBytes.Length, RemoteIpEndPoint);
    }
}

我尝试添加try / catch块来忽略异常并从方法返回,但是下次调用我的服务器查询方法而不是尝试查询下一个服务器时它会自动捕获,即使下一个服务器在线并且如果方法使用try块中的代码进行查询,则不会抛出异常。

到底有没有?

使用try / catch块的服务器查询方法:

private void QueryServer(IPAddress IP, int Port)
{
    try
    {
        udpClient.Connect(IP, Port);

        Byte[] sendBytes = Encoding.ASCII.GetBytes("\\100 * 1024\\");

        udpClient.Send(sendBytes, sendBytes.Length);

        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IP, Port);

        Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);

        string returnData = Encoding.ASCII.GetString(receiveBytes);

        if (returnData == "")
        {
            return;
        }
        else
        {
            ProcessPacket(receiveBytes, receiveBytes.Length, RemoteIpEndPoint);
        }
    }
    catch (Exception)
    {
        return;
    }
} 

0 个答案:

没有答案