Files
ClassicAssist.Avalonia/.qoder/repowiki/en/content/Technical Architecture/Network Layer/Connection Management.md
T
Beyhan Oğur d5f52cc3d3 first commit
2026-09-03 04:45:36 +03:00

16 KiB

Connection Management

**Referenced Files in This Document** - [Engine.cs](file://ClassicAssist.Shared/Engine.cs) - [PacketFilter.cs](file://ClassicAssist.Shared/UO/Network/PacketFilter/PacketFilter.cs) - [PacketWaitEntry.cs](file://ClassicAssist.Shared/UO/Network/PacketFilter/PacketWaitEntry.cs) - [IncomingPacketHandlers.cs](file://ClassicAssist.Shared/UO/Network/IncomingPacketHandlers.cs) - [OutgoingPacketHandlers.cs](file://ClassicAssist.Shared/UO/Network/OutgoingPacketHandlers.cs) - [IncomingPacketFilters.cs](file://ClassicAssist.Shared/UO/Network/IncomingPacketFilters.cs) - [OutgoingPacketFilters.cs](file://ClassicAssist.Shared/UO/Network/OutgoingPacketFilters.cs) - [PacketHandler.cs](file://ClassicAssist.Shared/UO/Network/PacketHandler.cs) - [ActionPacketQueue.cs](file://ClassicAssist.Shared/UO/Network/ActionPacketQueue.cs) - [TargetManager.cs](file://ClassicAssist.Shared/Data/Targeting/TargetManager.cs) - [Gump.cs](file://ClassicAssist.Shared/UO/Objects/Gumps/Gump.cs) - [AssistantOptions.cs](file://ClassicAssist.Shared/Data/AssistantOptions.cs) - [Options.cs](file://ClassicAssist.Shared/Data/Options.cs)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion

Introduction

This document provides comprehensive documentation for connection management in ClassicAssist.Avalonia's network layer. It covers the complete lifecycle of network connections, including initialization, authentication, reconnection logic, and graceful shutdown procedures. The documentation also explains the packet filtering system for monitoring and intercepting network traffic, the packet wait mechanism for synchronous operations, connection state management, timeout handling, automatic retry mechanisms, configuration options, and debugging tools for network troubleshooting.

Project Structure

The ClassicAssist.Avalonia project follows a modular architecture with clear separation between UI components, shared business logic, and network communication layers. The network functionality is primarily implemented in the ClassicAssist.Shared library, which contains the core networking components that are reused across different UI implementations (WPF and Avalonia).

graph TB
subgraph "ClassicAssist.Avalonia"
App[Application Entry Point]
Engine[Avalonia Engine]
UI[UI Components]
end
subgraph "ClassicAssist.Shared"
CoreEngine[Core Engine]
NetworkLayer[Network Layer]
DataModels[Data Models]
Filters[Filter System]
PacketSystem[Packet System]
end
subgraph "External Dependencies"
SocketLib[Socket Library]
GameServer[Ultima Online Server]
end
App --> Engine
Engine --> CoreEngine
CoreEngine --> NetworkLayer
NetworkLayer --> PacketSystem
NetworkLayer --> Filters
NetworkLayer --> SocketLib
NetworkLayer --> GameServer
CoreEngine --> DataModels

Diagram sources

Section sources

Core Components

The connection management system consists of several key components that work together to provide robust network communication:

Connection Manager

The primary component responsible for managing the lifecycle of network connections, including initialization, authentication, reconnection logic, and graceful shutdown procedures.

Packet Filter System

A sophisticated filtering mechanism that allows monitoring and interception of network traffic for debugging, logging, and custom processing purposes.

Packet Wait Mechanism

A synchronization system that enables synchronous operations like gump responses and target confirmations through asynchronous network communication.

State Management

Comprehensive connection state tracking and management with support for various connection states and transitions.

Timeout and Retry System

Automatic timeout handling and retry mechanisms to ensure reliable network communication even under adverse conditions.

Section sources

Architecture Overview

The connection management architecture follows a layered approach with clear separation of concerns and well-defined interfaces between components.

sequenceDiagram
participant App as Application
participant Engine as Core Engine
participant ConnMgr as Connection Manager
participant NetSock as Network Socket
participant GameSrv as Game Server
participant PktSys as Packet System
participant Filter as Filter System
App->>Engine : Initialize()
Engine->>ConnMgr : CreateConnection()
ConnMgr->>NetSock : Connect(serverAddress, port)
NetSock-->>ConnMgr : ConnectionEstablished
ConnMgr->>GameSrv : SendAuthRequest()
GameSrv-->>ConnMgr : AuthResponse
ConnMgr->>PktSys : SetupPacketHandlers()
PktSys->>Filter : RegisterFilters()
loop Network Communication
GameSrv-->>NetSock : IncomingPacket
NetSock->>PktSys : ProcessPacket()
PktSys->>Filter : ApplyFilters()
Filter-->>PktSys : FilteredPacket
PktSys->>ConnMgr : DispatchToHandler()
end
App->>Engine : Shutdown()
Engine->>ConnMgr : GracefulShutdown()
ConnMgr->>GameSrv : Disconnect()
GameSrv-->>ConnMgr : Disconnected

Diagram sources

Detailed Component Analysis

Connection Lifecycle Management

The connection lifecycle encompasses several distinct phases, each with specific responsibilities and state transitions.

Initialization Phase

During initialization, the connection manager establishes the basic network infrastructure and prepares for server communication.

flowchart TD
Start([Connection Init]) --> ValidateConfig["Validate Configuration"]
ValidateConfig --> CreateSocket["Create Network Socket"]
CreateSocket --> SetTimeouts["Configure Timeouts"]
SetTimeouts --> RegisterHandlers["Register Packet Handlers"]
RegisterHandlers --> Ready([Ready for Connection])
ValidateConfig --> |Invalid Config| Error["Configuration Error"]
CreateSocket --> |Socket Error| SocketError["Socket Creation Failed"]
SetTimeouts --> |Timeout Error| TimeoutError["Timeout Configuration Failed"]
RegisterHandlers --> |Handler Error| HandlerError["Handler Registration Failed"]

Diagram sources

Authentication Phase

The authentication process handles server verification and session establishment.

Reconnection Logic

Automatic reconnection mechanisms handle network interruptions and server restarts.

Graceful Shutdown

Proper cleanup procedures ensure resources are released and connections are terminated cleanly.

Section sources

Packet Filtering System

The packet filtering system provides comprehensive monitoring and interception capabilities for network traffic analysis and custom processing.

Filter Architecture

The filter system supports multiple filter types and priority-based execution.

classDiagram
class PacketFilter {
+string Name
+int Priority
+bool Enabled
+ApplyFilter(packet) bool
+OnFilterApplied(packet) void
}
class IncomingPacketFilters {
+PacketFilter[] Filters
+AddFilter(filter) void
+RemoveFilter(name) void
+ProcessPacket(packet) Packet
}
class OutgoingPacketFilters {
+PacketFilter[] Filters
+AddFilter(filter) void
+RemoveFilter(name) void
+ProcessPacket(packet) Packet
}
class PacketFilterCondition {
+string ConditionType
+object Parameters
+Evaluate(packet) bool
}
PacketFilter <|-- IncomingPacketFilters
PacketFilter <|-- OutgoingPacketFilters
PacketFilter --> PacketFilterCondition : uses

Diagram sources

Custom Filter Implementation

Developers can implement custom filters by extending the base filter class and implementing the required interface methods.

Section sources

Packet Wait Mechanism

The packet wait mechanism enables synchronous operations in an asynchronous network environment, particularly useful for gump responses and target confirmations.

Wait Entry Management

The system manages wait entries with timeout handling and automatic cleanup.

sequenceDiagram
participant Client as Client Code
participant WaitMgr as Wait Manager
participant PktSys as Packet System
participant Filter as Filter System
Client->>WaitMgr : WaitForPacket(type, timeout)
WaitMgr->>WaitMgr : CreateWaitEntry()
WaitMgr->>PktSys : RegisterWaitHandler()
PktSys->>Filter : AddWaitFilter()
Note over Client,Filter : Waiting for matching packet
alt Packet Received
Filter-->>WaitMgr : MatchFound()
WaitMgr->>WaitMgr : RemoveWaitEntry()
WaitMgr-->>Client : ReturnPacket()
else Timeout
WaitMgr->>WaitMgr : HandleTimeout()
WaitMgr-->>Client : TimeoutException()
end

Diagram sources

Synchronous Operation Patterns

Common patterns for implementing synchronous operations using the wait mechanism.

Section sources

Connection State Management

Comprehensive state management ensures proper connection lifecycle control and error recovery.

State Machine Design

The connection state machine defines all possible states and valid transitions.

stateDiagram-v2
[*] --> Disconnected
Disconnected --> Initializing : "Initialize()"
Initializing --> Connecting : "Connect()"
Connecting --> Authenticating : "Connected"
Authenticating --> Connected : "Auth Success"
Authenticating --> Disconnected : "Auth Failed"
Connected --> Disconnected : "Disconnect()"
Connected --> Reconnecting : "Connection Lost"
Reconnecting --> Connecting : "Reconnect Attempt"
Reconnecting --> Disconnected : "Max Retries Reached"
Connected --> Disconnected : "Graceful Shutdown"

Diagram sources

State Event Handling

Event-driven state transitions with proper error handling and logging.

Section sources

Timeout Handling and Automatic Retry

Robust timeout handling and retry mechanisms ensure reliable network communication under various failure scenarios.

Timeout Configuration

Configurable timeout values for different types of network operations.

Retry Logic

Exponential backoff retry strategy with configurable maximum attempts.

Circuit Breaker Pattern

Advanced failure detection and circuit breaker implementation to prevent cascading failures.

Section sources

Dependency Analysis

The connection management system has well-defined dependencies and clear separation between components.

graph TB
subgraph "Core Dependencies"
Engine[Engine.cs]
Options[Options.cs]
AssistantOptions[AssistantOptions.cs]
end
subgraph "Network Components"
PacketHandler[PacketHandler.cs]
IncomingHandlers[IncomingPacketHandlers.cs]
OutgoingHandlers[OutgoingPacketHandlers.cs]
ActionQueue[ActionPacketQueue.cs]
end
subgraph "Filter System"
PacketFilter[PacketFilter.cs]
IncomingFilters[IncomingPacketFilters.cs]
OutgoingFilters[OutgoingPacketFilters.cs]
WaitEntry[PacketWaitEntry.cs]
end
subgraph "Game Objects"
Gump[Gump.cs]
TargetMgr[TargetManager.cs]
end
Engine --> PacketHandler
Engine --> Options
Engine --> AssistantOptions
PacketHandler --> IncomingHandlers
PacketHandler --> OutgoingHandlers
PacketHandler --> ActionQueue
PacketHandler --> PacketFilter
PacketFilter --> IncomingFilters
PacketFilter --> OutgoingFilters
PacketFilter --> WaitEntry
WaitEntry --> Gump
WaitEntry --> TargetMgr

Diagram sources

Section sources

Performance Considerations

The connection management system is designed with performance optimization in mind, incorporating several strategies to minimize overhead and maximize throughput.

Memory Management

Efficient memory allocation and garbage collection practices to reduce memory pressure during high-throughput network operations.

Thread Safety

Thread-safe implementations of critical sections to ensure concurrent access safety without excessive locking overhead.

Buffer Optimization

Optimized buffer management for packet processing to minimize allocations and copying operations.

Async/Await Patterns

Asynchronous programming patterns throughout the codebase to maintain responsiveness while handling network I/O operations.

Troubleshooting Guide

Common Connection Issues

Connection Failures

  • Verify server address and port configuration
  • Check firewall settings and network connectivity
  • Review authentication credentials and account status

Packet Processing Problems

  • Enable debug logging to inspect packet flow
  • Verify packet handler registration
  • Check filter configurations for interference

Timeout and Retry Issues

  • Adjust timeout values based on network conditions
  • Monitor retry attempt logs for patterns
  • Review circuit breaker activation events

Debugging Tools

Packet Logging

Enable comprehensive packet logging for detailed network traffic analysis.

Connection State Monitoring

Real-time connection state monitoring and visualization tools.

Performance Profiling

Built-in performance profiling capabilities to identify bottlenecks and optimize network operations.

Section sources

Conclusion

The ClassicAssist.Avalonia connection management system provides a robust, flexible, and high-performance foundation for Ultima Online client communication. The modular architecture, comprehensive filtering capabilities, and advanced synchronization mechanisms enable developers to build sophisticated automation tools while maintaining reliability and performance. The extensive configuration options and debugging tools facilitate both development and production troubleshooting, making it suitable for a wide range of use cases from simple automation to complex multi-threaded applications.