Files

79 lines
7.8 KiB
Markdown
Raw Permalink Normal View History

2026-04-17 14:55:32 -04:00
---
source_files:
- Common/DTS.Common/Interface/Connection/IConnection.cs
generated_at: "2026-04-16T02:59:48.622286+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "06a808aff2343a50"
---
# Connection
### **Purpose**
This module defines the `IConnection` interface, which abstracts network connection semantics for a proprietary DTS (likely *Device Tracking System* or similar) platform. It provides a unified contract for managing connection lifecycle (connect, disconnect, reconnect), asynchronous I/O operations (send/receive), and connection state tracking—including special handling for *soft disconnections*, where disconnection is intentional and reversible. The interface supports both synchronous and asynchronous patterns (including APM-style `Begin`/`End` methods), enabling flexible integration with legacy and modern async code while maintaining low-level socket control (e.g., `SocketFlags`, `Bind`, `Listen`, `Accept`). It serves as the foundational abstraction for device communication layers, likely implemented by concrete socket- or transport-specific classes.
---
### **Public Interface**
| Member | Signature | Behavior |
|--------|-----------|----------|
| `SendAsync` | `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` | Sends data asynchronously. Returns the number of bytes sent. |
| `IsSoftDisconnected` | `bool IsSoftDisconnected { get; }` | Returns `true` if the connection was *soft disconnected* (i.e., voluntarily disconnected with intent to reconnect later). |
| `SoftDisconnect` | `void SoftDisconnect()` | Voluntarily disconnects the connection with the expectation of reconnection (does *not* fully tear down resources). |
| `SoftConnect` | `void SoftConnect()` | Reconnects a connection previously soft-disconnected. |
| `Flags` | `System.Net.Sockets.SocketFlags Flags { get; set; }` | Gets or sets socket flags used during send/receive operations. |
| `OnDisconnected` | `event EventHandler OnDisconnected` | Raised when the connection is fully disconnected (not just soft-disconnected). |
| `KeepAliveErrorReceived` | `void KeepAliveErrorReceived()` | Indicates that a keep-alive timeout occurred (device did not receive timely response). Likely triggers reconnection logic. |
| `ConnectString` | `string ConnectString { get; }` | Returns the connection string used to establish the connection. |
| `Connected` | `bool Connected { get; }` | Returns `true` if the connection is currently active (not disconnected or soft-disconnected). |
| `Create` (overload 1) | `void Create(string connectString)` | Initializes the connection using a single connection string. |
| `Create` (overload 2) | `void Create(string connectString, string hostIPAddress)` | Initializes the connection using a connection string and explicit host IP address. |
| `GetConnectionData` | `string GetConnectionData()` | Returns diagnostic or metadata information about the current connection state. |
| `BeginConnect` / `EndConnect` | `IAsyncResult BeginConnect(AsyncCallback callback, object callbackObject)`<br>`void EndConnect(IAsyncResult ar)` | Asynchronous connection initiation (APM pattern). |
| `BeginDisconnect` / `EndDisconnect` | `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)`<br>`void EndDisconnect(IAsyncResult asyncResult)` | Asynchronous disconnection (APM pattern); `reuseSocket` indicates whether the underlying socket can be reused. |
| `BeginAccept` / `EndAccept` | `IAsyncResult BeginAccept(AsyncCallback callback, object state)`<br>`IConnection EndAccept(IAsyncResult asyncResult)` | Asynchronous accept for server-side connections (APM pattern); returns a new `IConnection` for the accepted client. |
| `Bind` | `void Bind(int port)` | Binds the connection to a local port (typically for server-side use). |
| `Listen` | `void Listen(int backlog)` | Begins listening for incoming connections (server-side). |
| `BeginSend` / `EndSend` | `IAsyncResult BeginSend(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend, AsyncCallback callback, object callbackObject)`<br>`int EndSend(IAsyncResult ar)` | Asynchronous send (APM pattern). Returns bytes sent. |
| `BeginReceive` / `EndReceive` | `IAsyncResult BeginReceive(byte[] receiveBuffer, int bufferStartOffset, int maxSizeToReceive, AsyncCallback callback, object callbackObject)`<br>`int EndReceive(IAsyncResult ar)` | Asynchronous receive (APM pattern). Returns number of bytes received. |
> **Note**: Two methods (`GetCurrentUploadRate`, `GetCurrentDownloadRate`) are commented out and thus *not part of the public interface*.
---
### **Invariants**
- `Connected` must be `false` when `IsSoftDisconnected` is `true`.
- `SoftDisconnect()` must set `IsSoftDisconnected = true` and raise `OnDisconnected` *only if* the disconnection is final (not soft). Since soft disconnects are *intended to be reversible*, `OnDisconnected` is likely *not* raised during `SoftDisconnect()`.
- `SoftConnect()` must restore `Connected = true` and `IsSoftDisconnected = false` without requiring full re-initialization (e.g., re-binding/listening if server-side).
- `Flags` must be applied consistently to all socket operations (`Send`, `Receive`, `Accept`, etc.).
- `ConnectString` must remain immutable after initialization (set via `Create`).
- `KeepAliveErrorReceived()` must be called *only* when a keep-alive timeout occurs, and likely triggers `SoftDisconnect()` internally (implementation-dependent but implied by naming).
---
### **Dependencies**
- **Depends on**:
- `System` (core types: `EventHandler`, `IAsyncResult`, `AsyncCallback`, `Object`)
- `System.Threading.Tasks` (for `Task<int>`)
- `System.Net.Sockets` (for `SocketFlags`)
- **Implied dependencies**:
- Concrete implementations likely depend on `System.Net.Sockets.Socket` (for low-level socket operations).
- May depend on internal logging, timing, or keep-alive services (not visible in interface but implied by `KeepAliveErrorReceived`).
- **Depended on by**:
- Higher-level connection managers or device drivers (e.g., `IDevice`, `ConnectionManager`) that consume `IConnection` for communication.
- Unit tests or mock frameworks (due to clear interface boundaries).
---
### **Gotchas**
- **Soft vs. Hard Disconnection**: `SoftDisconnect()` does *not* imply `Connected = false`; `Connected` remains `true` until a *hard* disconnect (e.g., via `EndDisconnect` or network failure). `IsSoftDisconnected` is the correct state to check for intentional disconnection.
- **APM Pattern Consistency**: `BeginAccept` returns `IConnection` (not `IAsyncResult`), and `EndAccept` returns a *new* `IConnection` instance—this suggests the interface supports server-side connection multiplexing.
- **`reuseSocket` in `BeginDisconnect`**: The `bool reuseSocket` parameter indicates socket reuse semantics (e.g., for `SO_REUSEADDR`), but behavior is implementation-defined. Misuse may cause socket exhaustion.
- **`KeepAliveErrorReceived()` is a *notification*, not a trigger**: It signals an error condition but does *not* automatically disconnect; callers must handle reconnection logic (e.g., by calling `SoftDisconnect()`).
- **`Create` overloads**: The two `Create` methods suggest dual-mode initialization (e.g., client vs. server), but the distinction is unclear without implementation details. `hostIPAddress` may be redundant with `connectString`.
- **No cancellation support**: All async methods lack `CancellationToken`—legacy APM-only design may complicate modern async/await integration.
- **No return value for `SoftConnect`/`SoftDisconnect`**: No indication of success/failure; exceptions likely used for error reporting (not documented here).
- **`GetCurrentUploadRate`/`GetCurrentDownloadRate` commented out**: Rate-monitoring functionality is deprecated or incomplete; do not rely on it.
> **None identified from source alone** for additional gotchas beyond those listed.