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