# Network Chat Client - Technical Documentation

**Author: Molla Samser (Founder, RSK World)**  
**Designer & Tester: Rima Khatun**  
**Website: https://rskworld.in**  
**Year: 2026**

## Table of Contents

1. [Architecture Overview](#architecture-overview)
2. [Network Protocol](#network-protocol)
3. [Threading Model](#threading-model)
4. [Security Implementation](#security-implementation)
5. [Message Flow](#message-flow)
6. [Error Handling](#error-handling)
7. [Performance Considerations](#performance-considerations)
8. [API Reference](#api-reference)
9. [Troubleshooting Guide](#troubleshooting-guide)

## Architecture Overview

### Client-Server Model

The Network Chat Client implements a classic client-server architecture:

```
┌─────────────┐    TCP/IP     ┌─────────────┐    TCP/IP     ┌─────────────┐
│   Client 1  │ ◄──────────► │   Server    │ ◄──────────► │   Client 2  │
└─────────────┘              └─────────────┘              └─────────────┘
       ▲                            ▲                            ▲
       │                            │                            │
┌─────────────┐              ┌─────────────┐              ┌─────────────┐
│   Client 3  │              │   Client N  │              │   Client N  │
└─────────────┘              └─────────────┘              └─────────────┘
```

### Component Architecture

#### Client Components
- **ChatClient Class**: Main client logic
- **Network Layer**: Socket communication
- **Encryption Layer**: Message encryption/decryption
- **UI Layer**: Command-line interface

#### Server Components
- **ChatServer Class**: Main server logic
- **Connection Manager**: Client connection handling
- **Message Router**: Message distribution
- **Authentication Module**: User verification

## Network Protocol

### Message Format

All messages follow this format:
```
TYPE:SENDER:RECEIVER:CONTENT:TIMESTAMP
```

#### Message Types
- `AUTH` - Authentication request
- `MESSAGE` - Regular message
- `BROADCAST` - Broadcast to all users
- `PRIVATE` - Private message
- `DISCONNECT` - Client disconnect
- `ERROR` - Error message

#### Protocol Examples

**Authentication:**
```
AUTH:username:password:session_key
```

**Broadcast Message:**
```
BROADCAST:alice::Hello everyone!:2026-01-28 22:30:00
```

**Private Message:**
```
PRIVATE:alice:bob:Hi Bob!:2026-01-28 22:30:15
```

## Threading Model

### Client Threading

```
Main Thread
├── User Input Handling
├── Command Processing
└── UI Updates

Receive Thread
├── Socket Monitoring
├── Message Reception
└── Message Decryption

Send Thread
├── Message Queue
├── Message Encryption
└── Socket Transmission
```

### Server Threading

```
Main Thread
├── Server Commands
├── Statistics Display
└── Administrative Tasks

Accept Thread
├── Socket Listening
├── Connection Acceptance
└── Client Thread Creation

Client Threads (N)
├── Client Communication
├── Message Processing
└── Disconnect Handling
```

### Thread Synchronization

#### Mutex Usage
- `clientsMutex`: Protects client list
- `messageMutex`: Protects message history
- `networkMutex`: Protects socket operations

#### Atomic Operations
- `isRunning`: Server/client state
- `isConnected`: Connection status
- `clientCount`: Active client count

## Security Implementation

### Encryption Scheme

Currently uses XOR encryption (educational purposes):

```cpp
std::string encryptMessage(const std::string& message) {
    std::string encrypted = message;
    for (size_t i = 0; i < message.length() && i < sessionKey.length(); ++i) {
        encrypted[i] ^= sessionKey[i % sessionKey.length()];
    }
    return encrypted;
}
```

### Session Management

#### Session Key Generation
```cpp
std::string generateSessionKey() {
    std::string key = "RSK_WORLD_2026_CHAT_KEY";
    key += std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
    return key.substr(0, 32);
}
```

#### Authentication Flow
1. Client sends username/password
2. Server validates credentials
3. Server generates session key
4. Client receives authentication confirmation
5. All subsequent messages encrypted with session key

### Security Recommendations

For production use:
1. Replace XOR with AES-256
2. Implement SSL/TLS certificates
3. Add rate limiting
4. Implement proper user database
5. Add input sanitization

## Message Flow

### Client Connection Flow

```
1. Client Start
   ↓
2. Initialize Winsock
   ↓
3. Connect to Server
   ↓
4. Authenticate User
   ↓
5. Start Threads
   ↓
6. Begin Chat Session
```

### Message Processing Flow

```
1. User Input
   ↓
2. Command Parsing
   ↓
3. Message Formatting
   ↓
4. Message Encryption
   ↓
5. Socket Transmission
   ↓
6. Server Processing
   ↓
7. Message Routing
   ↓
8. Client Reception
   ↓
9. Message Decryption
   ↓
10. Display Message
```

### Broadcast Message Flow

```
Client A → Server → All Clients (except A)
```

### Private Message Flow

```
Client A → Server → Client B
```

## Error Handling

### Network Errors

#### Connection Errors
- `WSAETIMEDOUT`: Connection timeout
- `WSAECONNREFUSED`: Connection refused
- `WSAEHOSTUNREACH`: Host unreachable

#### Socket Errors
- `WSAEWOULDBLOCK`: Non-blocking operation
- `WSAENOTCONN`: Socket not connected
- `WSAECONNRESET`: Connection reset

### Error Recovery Strategies

#### Client Side
1. Automatic reconnection attempts
2. Graceful degradation
3. User notification

#### Server Side
1. Client cleanup
2. Resource release
3. Logging and monitoring

### Logging Implementation

```cpp
void logActivity(const std::string& activity) {
    std::cout << "[" << getCurrentTimestamp() << "] " << activity << std::endl;
}
```

## Performance Considerations

### Memory Management

#### Client Memory Usage
- Message history: 100 messages max
- Buffer size: 4096 bytes
- Thread stack: Default size

#### Server Memory Usage
- Client pool: 100 clients max
- Message history: 1000 messages max
- Per-client buffer: 4096 bytes

### Network Optimization

#### Buffer Management
```cpp
#define MAX_BUFFER_SIZE 4096
char buffer[MAX_BUFFER_SIZE];
```

#### Non-blocking Sockets
```cpp
u_long mode = 1; // Non-blocking
ioctlsocket(clientSocket, FIONBIO, &mode);
```

### CPU Optimization

#### Thread Sleep Intervals
```cpp
std::this_thread::sleep_for(std::chrono::milliseconds(100));
```

#### Cleanup Interval
```cpp
std::this_thread::sleep_for(std::chrono::seconds(30));
```

## API Reference

### ChatClient Class

#### Constructors
```cpp
ChatClient();  // Default constructor
~ChatClient(); // Destructor
```

#### Core Methods
```cpp
bool initialize();                           // Initialize client
bool start(const std::string& serverIP, int port); // Start connection
void stop();                                 // Stop client
void run();                                  // Main loop
```

#### Message Methods
```cpp
void sendMessage(const std::string& content, const std::string& receiver = "");
void sendBroadcast(const std::string& content);
void sendPrivateMessage(const std::string& receiver, const std::string& content);
```

#### Utility Methods
```cpp
void displayHelp();                          // Show commands
void displayMessageHistory();                // Show history
void clearScreen();                          // Clear terminal
bool isConnectedToServer() const;             // Check connection
```

### ChatServer Class

#### Constructors
```cpp
ChatServer();  // Default constructor
~ChatServer(); // Destructor
```

#### Core Methods
```cpp
bool initialize(int port = DEFAULT_PORT);    // Initialize server
bool start();                                // Start listening
void stop();                                 // Stop server
void run();                                  // Main loop
```

#### Administrative Methods
```cpp
void kickClient(const std::string& username); // Kick user
void broadcastServerMessage(const std::string& message); // Server message
void displayServerStats();                   // Show statistics
void displayMessageHistory();                // Show history
```

#### Statistics Methods
```cpp
int getConnectedClientsCount() const;        // Client count
int getAuthenticatedClientsCount() const;    // Authenticated count
std::vector<std::string> getOnlineUsers();   // Online users
```

## Troubleshooting Guide

### Common Issues

#### 1. Connection Failed

**Symptoms:**
- Client cannot connect to server
- "Connection to server failed" error

**Causes:**
- Server not running
- Wrong IP address or port
- Firewall blocking connection

**Solutions:**
```bash
# Check if server is running
netstat -an | findstr :54000

# Test connectivity
telnet 127.0.0.1 54000

# Check firewall
# Allow port 54000 in Windows Firewall
```

#### 2. Authentication Failed

**Symptoms:**
- "Authentication failed" message
- Cannot join chat

**Causes:**
- Username already taken
- Invalid username format
- Network issues during auth

**Solutions:**
```bash
# Username requirements:
# - 3-20 characters
# - No duplicates
# - Alphanumeric only
```

#### 3. Compilation Errors

**Symptoms:**
- Linker errors
- Missing headers
- OpenSSL not found

**Solutions:**
```cmake
# Ensure OpenSSL is installed and paths are correct
find_package(OpenSSL REQUIRED)
target_link_libraries(chat_client ${OPENSSL_LIBRARIES})
```

#### 4. Runtime Crashes

**Symptoms:**
- Application crashes
- Access violations

**Causes:**
- Null pointer access
- Socket misuse
- Thread synchronization issues

**Debugging:**
```cpp
// Enable debug mode
#define DEBUG_MODE

// Add debug prints
#ifdef DEBUG_MODE
std::cout << "Debug: " << message << std::endl;
#endif
```

### Performance Issues

#### High CPU Usage

**Causes:**
- Tight loops without sleep
- Excessive thread creation
- Inefficient polling

**Solutions:**
```cpp
// Add sleep to loops
std::this_thread::sleep_for(std::chrono::milliseconds(100));

// Use thread pools
// Limit thread creation
```

#### Memory Leaks

**Detection:**
```cpp
// Use Visual Studio debugger
// Enable memory leak detection
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
```

**Prevention:**
```cpp
// RAII principles
// Smart pointers
// Proper cleanup in destructors
```

### Network Issues

#### Packet Loss

**Symptoms:**
- Messages not arriving
- Delayed delivery

**Solutions:**
- TCP handles reliability automatically
- Check network stability
- Implement retry logic if needed

#### Connection Timeouts

**Configuration:**
```cpp
// Set socket timeout
int timeout = 5000; // 5 seconds
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
```

## Development Guidelines

### Code Style

#### Naming Conventions
- Classes: PascalCase (ChatClient)
- Functions: camelCase (sendMessage)
- Variables: camelCase (clientSocket)
- Constants: UPPER_CASE (MAX_BUFFER_SIZE)

#### Documentation
- Header comments for all functions
- Inline comments for complex logic
- Doxygen style documentation

### Testing

#### Unit Tests
```cpp
// Test message encryption
void testEncryption() {
    ChatClient client;
    std::string original = "Hello World";
    std::string encrypted = client.encryptMessage(original);
    std::string decrypted = client.decryptMessage(encrypted);
    assert(original == decrypted);
}
```

#### Integration Tests
- Client-server communication
- Multi-client scenarios
- Network failure simulation

### Future Enhancements

#### Security Improvements
- AES-256 encryption
- SSL/TLS implementation
- Two-factor authentication
- Rate limiting

#### Feature Additions
- File transfer capability
- Voice chat support
- Video conferencing
- Group chat rooms
- Message persistence
- User profiles

#### Performance Improvements
- Asynchronous I/O
- Connection pooling
- Load balancing
- Caching mechanisms

---

**Contact Information:**  
- **Website**: https://rskworld.in  
- **Email**: info@rskworld.com, support@rskworld.com  
- **Phone**: +91 93305 39277  
- **Address**: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

© 2026 RSK World. All rights reserved.
