c# - 由于线程退出或应用程序请求,I/O 操作已中止

标签 c# sockets exception

我的应用程序用作银行服务器的客户端应用程序。该应用程序正在发送请求并从银行获得响应。此应用程序通常运行良好,但有时

The I/O operation has been aborted because of either a thread exit or an application request

错误代码为 995。

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", 
                                        ref swReceivedLogWriter, strLogPath, 0);
    try
    {
        SocketPacket theSockId = (SocketPacket)asyn.AsyncState;

        int iRx = theSockId.thisSocket.EndReceive(asyn); //Here error is coming
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

    }
}

一旦在同样的错误开始出现之后,所有交易开始出现这个错误,所以 请帮我解决这个问题。如果可能的话,使用一些示例代码

问候, 阿希什·坎德尔瓦尔

最佳答案

995 是 IO Completion Port 报告的错误.出现此错误是因为您在套接字很可能已关闭时尝试继续读取它。

EndRecieve 接收到 0 个字节意味着套接字已关闭,EndRecieve 将抛出的大多数异常也是如此。

您需要开始处理这些情况。

永远不要忽略异常,它们的抛出是有原因的。

更新

没有任何迹象表明服务器做错了什么。连接丢失的原因有很多,例如空闲连接被交换机/路由器/防火墙关闭、网络不稳定、电缆损坏等。

我的意思是您必须处理断开连接。这样做的正确方法是处理套接字,并在一定的时间间隔尝试连接一个新套接字。

至于接收回调更合适的处理方式是这样的(半伪代码):

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);

    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;

        int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
        if (bytesReceived == 0)
        {
          HandleDisconnect(client);
          return;
        }
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }

    try
    {
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

        //do your handling here
    }
    catch (Exception err)
    {
        // Your logic threw an exception. handle it accordinhly
    }

    try
    {
       client.thisSocket.BeginRecieve(.. all parameters ..);
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }
}

我使用三个 catch block 的原因很简单,因为中间一个的逻辑与其他两个不同。来自 BeginReceive/EndReceive 的异常通常表示套接字断开连接,而来自您的逻辑的异常不应停止套接字接收。

关于c# - 由于线程退出或应用程序请求,I/O 操作已中止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7228703/

相关文章:

c++ - 获取传入连接的源IP地址

c# - NUnit 测试用例预期消息

c# - 可以中止 MVC 操作并保持 View 不变(无需重写 View 的 GET "load code")?

C# 和 Moq - 如何断言未引发事件

Java套接字,简单的多人游戏,发送数据

java - 异常处理 try-catch 语句字符串长度

c# - 异常处理(矛盾的文档/尝试最终与使用)

c# - 我究竟做错了什么? wcf 和 Entity Framework

c# - 如何在 DI 设置期间自动验证 appSettings.json 文件中的配置值?

c - 使用C在套接字编程中获取请求的地址