Handling Socket Disconnections in C#: A Comprehensive Guide to Error 995

Dec 02, 2025 · Programming · 16 views · 7.8

Keywords: C# | Sockets | Error Handling

Abstract: This article explores the common socket error 'The I/O operation has been aborted' with code 995 in C# applications. It analyzes the causes, provides a best-practice solution for handling disconnections, includes code examples, and discusses additional considerations from other answers.

Introduction

When developing client applications in C# that use sockets for communication, such as with a bank server, developers may encounter the error "The I/O operation has been aborted because of either a thread exit or an application request" with error code 995. This error often indicates that the socket has been closed unexpectedly, leading to interruptions in data transmission.

Error Analysis

Error code 995 is reported by the I/O Completion Port and typically occurs when attempting to read from a socket that has been closed. This can happen due to network issues, idle connections being terminated by intermediate devices, or application-level requests to abort operations.

Solution Based on Best Practice

To handle this error effectively, it is crucial to implement proper disconnection handling. The recommended approach involves checking the bytes received from EndReceive and catching exceptions to detect socket closures. Upon detection, the socket should be disposed, and reconnection logic implemented.

Code Implementation

Here is an enhanced version of the OnDataReceived method based on the best answer:

public void OnDataReceived(IAsyncResult asyn)
{
    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;
        int bytesReceived = client.thisSocket.EndReceive(asyn);
        if (bytesReceived == 0)
        {
            HandleDisconnect(client);
            return;
        }
        // Process received data
        string strHEX = BLCommonFunctions.ByteArrToHex(client.dataBuffer);
        // Handle data logic here
    }
    catch (Exception err)
    {
        HandleDisconnect(client);
    }
    try
    {
        // Continue receiving
        client.thisSocket.BeginReceive(client.dataBuffer, 0, client.dataBuffer.Length, SocketFlags.None, OnDataReceived, client);
    }
    catch (Exception err)
    {
        HandleDisconnect(client);
    }
}

In this code, exceptions are caught separately to distinguish between socket disconnections and logic errors, ensuring robust error handling.

Additional Considerations

Other answers provide supplementary insights. For instance, increasing timeout settings in HttpClient might help in some scenarios, as suggested in Answer 2. However, this is more relevant for HTTP-based communication rather than raw sockets. Answer 3 discusses asynchronous waits for slow serial communication, which can be adapted for similar cases where operation completion needs verification.

Conclusion

Properly handling socket disconnections is essential for building reliable C# applications. By implementing exception handling and reconnection strategies, developers can mitigate errors like 995 and ensure smoother network communication. Always test under various network conditions to validate the robustness of the solution.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.