Skip to content

Latest commit

 

History

History
637 lines (513 loc) · 16.4 KB

File metadata and controls

637 lines (513 loc) · 16.4 KB

Socket Programming - Examples and Usage

Overview

This document provides comprehensive examples demonstrating the functionality of all three socket programming tasks with real-world usage scenarios.

Task 1: Hostname to IP Converter Examples

Basic Usage Examples

Example 1: Popular Websites

=== Hostname to IP Address Converter ===
Enter hostnames to convert to IP addresses.
Type 'exit' or 'quit' to terminate the program.

Enter hostname: google.com
Resolution Results:
------------------
Hostname: google.com
Primary IP Address: 142.250.191.14
All IP Addresses:
  1. 142.250.191.14 (IPv4)
  2. 2607:f8b0:4004:c1b::71 (IPv6)
Address Type Information:
  - IPv4 address

Enter hostname: github.com
Resolution Results:
------------------
Hostname: github.com
Primary IP Address: 140.82.113.4
Canonical Name: github.com
Address Type Information:
  - IPv4 address

Enter hostname: localhost
Resolution Results:
------------------
Hostname: localhost
Primary IP Address: 127.0.0.1
Address Type Information:
  - Loopback address (localhost)
  - IPv4 address

Example 2: Error Handling

Enter hostname: invalid.nonexistent.domain
Error: Unable to resolve hostname 'invalid.nonexistent.domain'
Possible causes:
  - Hostname does not exist
  - Network connectivity issues
  - DNS server problems
Please check the hostname and try again.

Enter hostname: 
Error: Please enter a hostname.

Enter hostname: [very-long-hostname-over-255-characters...]
Error: Hostname too long (maximum 255 characters).

Example 3: International Domains

Enter hostname: münchen.de
Resolution Results:
------------------
Hostname: münchen.de
Primary IP Address: 185.53.177.52
Address Type Information:
  - IPv4 address

Enter hostname: 中国.cn
Resolution Results:
------------------
Hostname: 中国.cn
Primary IP Address: 101.226.103.106
Address Type Information:
  - IPv4 address

Educational Use Cases

Computer Networks Class Demonstration

// Demonstrate DNS resolution concepts
public class DNSDemo {
    public static void main(String[] args) {
        // Students can see real-time DNS resolution
        // Understanding of IP addressing
        // IPv4 vs IPv6 differences
        // Local vs remote resolution
    }
}

Task 2: Ping-Pong Application Examples

Server Operation Examples

Example 1: Server Startup and Client Connections

=== Ping-Pong Server Started ===
Port: 12345
Max Connections: 50
Client Timeout: 30000ms
Waiting for client connections...
Press Ctrl+C to stop the server
=====================================

Client #1 connected from: 192.168.1.100:52847
Client #1 handler started
Client #1 sent: "ping"
Client #1 ← sent: "pong"
Client #1 sent: "hello"
Client #1 message dropped (not a ping)
Client #1 sent: "PING"
Client #1 ← sent: "pong"

Client #2 connected from: 192.168.1.101:52848
Client #2 handler started
Client #2 sent: "test message"
Client #2 message dropped (not a ping)

Client #1 disconnected and cleaned up
Active Clients: 1

Client Interaction Examples

Example 1: Basic Ping-Pong Testing

=====================================
    Ping-Pong Client Application    
=====================================
✓ Connected successfully!
Server: /127.0.0.1:12345
Local: /127.0.0.1:52847

Enter command: ping
→ Sent: "ping"
← Received: "pong"

Enter command: hello
→ Sent: "hello"
← No response (message likely dropped by server)

Enter command: PING
→ Sent: "PING"
← Received: "pong"

Enter command: test
Running Automated Test Sequence...
─────────────────────────────────────
Test: "ping"
→ Sent: "ping"
← Received: "pong"

Test: "PING"
→ Sent: "PING"
← Received: "pong"

Test: "hello"
→ Sent: "hello"
← No response (message likely dropped by server)

[Additional test cases...]

Automated test sequence completed.

Example 2: Multi-Client Scenario

# Terminal 1 - Client A
Enter command: ping
→ Sent: "ping"
← Received: "pong"

# Terminal 2 - Client B (simultaneous)
Enter command: hello
→ Sent: "hello" 
← No response (message likely dropped by server)

# Terminal 3 - Client C (simultaneous)
Enter command: PING
→ Sent: "PING"
← Received: "pong"

# All clients operate independently without interference

Educational Scenarios

Protocol Design Learning

// Students learn about:
// 1. Request-response patterns
// 2. Message filtering and validation
// 3. Stateless vs stateful protocols
// 4. Error handling in distributed systems

// Example protocol variations students can explore:
// - Echo server (responds with the same message)
// - Math server (processes mathematical expressions)
// - Chat server (broadcasts messages to all clients)

Concurrent Programming Concepts

// Multi-threading demonstration:
// - Each client handled by separate thread
// - Thread safety with shared resources
// - Resource cleanup and lifecycle management
// - Scalability considerations

Task 3: Uppercase Converter Examples

Server Operation Examples

Example 1: Message Processing with Logging

==========================================
    Uppercase Message Converter Server   
==========================================
Port: 54321
Max Connections: 50
Client Timeout: 30000ms
Max Message Length: 1024 characters
Character Encoding: UTF-8
Server Status: RUNNING
==========================================

Client #1 connected
  Remote Address: 127.0.0.1:52847
  Active Clients: 1

Client #1 handler started and ready
Client #1 [Msg #1] received: "hello world"
Client #1 [Msg #1] sent: "HELLO WORLD"

Client #1 [Msg #2] received: "Java Programming"
Client #1 [Msg #2] sent: "JAVA PROGRAMMING"

Client #1 [Msg #3] received: "café naïve"
Client #1 [Msg #3] sent: "CAFÉ NAÏVE"

Client #2 connected
  Remote Address: 127.0.0.1:52848
  Active Clients: 2

# Concurrent processing of multiple clients
Client #1 [Msg #4] received: "test message one"
Client #2 [Msg #1] received: "test message two"
Client #1 [Msg #4] sent: "TEST MESSAGE ONE"
Client #2 [Msg #1] sent: "TEST MESSAGE TWO"

Client Interaction Examples

Example 1: Basic Text Conversion

═══════════════════════════════════════════
   Uppercase Message Converter Client      
═══════════════════════════════════════════
✓ Connected successfully!
Server: /127.0.0.1:54321

Uppercase> hello world

[Message #1]
→ Sending: "hello world"
← Received: "HELLO WORLD"
ℹ Converted 10 character(s) to uppercase

Uppercase> Java Programming Rocks!

[Message #2]
→ Sending: "Java Programming Rocks!"
← Received: "JAVA PROGRAMMING ROCKS!"
ℹ Converted 18 character(s) to uppercase

Uppercase> 123 Test @#$

[Message #3]
→ Sending: "123 Test @#$"
← Received: "123 TEST @#$"
ℹ Converted 4 character(s) to uppercase

Example 2: International Character Support

Uppercase> café naïve résumé

[Message #4]
→ Sending: "café naïve résumé"
← Received: "CAFÉ NAÏVE RÉSUMÉ"
ℹ Converted 13 character(s) to uppercase

Uppercase> Müller Straße

[Message #5]
→ Sending: "Müller Straße"
← Received: "MÜLLER STRASSE"
ℹ Converted 12 character(s) to uppercase

Uppercase> Здравствуй мир

[Message #6]
→ Sending: "Здравствуй мир"
← Received: "ЗДРАВСТВУЙ МИР"
ℹ Converted 12 character(s) to uppercase

Uppercase> こんにちは world

[Message #7]
→ Sending: "こんにちは world"
← Received: "こんにちは WORLD"
ℹ Converted 5 character(s) to uppercase

Example 3: Automated Testing Suite

Uppercase> test

==================================================
           AUTOMATED TEST SEQUENCE
==================================================
Running 10 test cases...

Test Case 1/10:
[Message #8]
→ Sending: "hello world"
← Received: "HELLO WORLD"
ℹ Converted 10 character(s) to uppercase

Test Case 2/10:
[Message #9]
→ Sending: "Java Programming"
← Received: "JAVA PROGRAMMING"
ℹ Converted 13 character(s) to uppercase

Test Case 3/10:
[Message #10]
→ Sending: "ALREADY UPPERCASE"
← Received: "ALREADY UPPERCASE"
ℹ Note: Message was already in uppercase

Test Case 4/10:
[Message #11]
→ Sending: "lowercase text"
← Received: "LOWERCASE TEXT"
ℹ Converted 13 character(s) to uppercase

Test Case 5/10:
[Message #12]
→ Sending: "Mixed CaSe TeXt"
← Received: "MIXED CASE TEXT"
ℹ Converted 9 character(s) to uppercase

Test Case 6/10:
[Message #13]
→ Sending: "123 Numbers and Symbols!@#"
← Received: "123 NUMBERS AND SYMBOLS!@#"
ℹ Converted 16 character(s) to uppercase

Test Case 7/10:
[Message #14]
→ Sending: "Café naïve résumé"
← Received: "CAFÉ NAÏVE RÉSUMÉ"
ℹ Converted 13 character(s) to uppercase

Test Case 8/10:
[Message #15]
→ Sending: ""
← Received: ""

Test Case 9/10:
[Message #16]
→ Sending: "a"
← Received: "A"
ℹ Converted 1 character(s) to uppercase

Test Case 10/10:
[Message #17]
→ Sending: "A very long message to test the server's ability to handle longer text inputs without issues"
← Received: "A VERY LONG MESSAGE TO TEST THE SERVER'S ABILITY TO HANDLE LONGER TEXT INPUTS WITHOUT ISSUES"
ℹ Converted 76 character(s) to uppercase

==================================================
        AUTOMATED TESTING COMPLETED
==================================================

Example 4: Error Handling and Edge Cases

Uppercase> [attempting to send 1025+ character message]

[Message #18]
→ Sending: "[very long message exceeding limit...]"
✗ Server Error: Message too long (max 1024 characters)

Uppercase> status

Connection Status:
───────────────────────────────────────────
Connected: ✓ Yes
Server: localhost:54321
Remote Address: /127.0.0.1:54321
Local Address: /127.0.0.1:52847
Socket Open: true
Messages Sent: 18
Response Timeout: 5000ms
Max Message Length: 1024
───────────────────────────────────────────

Uppercase> stats

Session Statistics:
───────────────────────────────────────────
Messages Processed: 18
Connection Status: Active
Server Endpoint: localhost:54321
───────────────────────────────────────────

Real-World Application Scenarios

Technical Interview Preparation

// Common Interview Questions Covered:

// 1. "Implement a simple echo server"
//    → Use Task 2 as foundation, modify to echo messages

// 2. "How would you handle 1000 concurrent clients?"
//    → Discuss thread pools, NIO, scaling strategies

// 3. "Design a protocol for text processing service"
//    → Use Task 3 as example, extend with additional features

// 4. "How do you handle network failures?"
//    → Demonstrate error handling from all tasks

Portfolio Project Enhancement

// Extensions for Portfolio:

// 1. Add REST API endpoints
// 2. Implement database persistence
// 3. Add authentication and authorization
// 4. Create web-based management interface
// 5. Add metrics and monitoring
// 6. Implement load balancing
// 7. Add configuration management
// 8. Create Docker containers

Advanced Usage Patterns

Integration Testing Examples

Multi-Application Testing

# Terminal 1: Start all servers
./run-servers.bat

# Terminal 2: Test Task 1
java -cp task1-hostname-converter/src HostnameToIP
# Test DNS resolution for server hostnames

# Terminal 3: Test Task 2
java -cp task2-ping-pong/src client.PingPongClient
# Verify ping-pong functionality

# Terminal 4: Test Task 3
java -cp task3-uppercase-converter/src client.UppercaseClient
# Test message conversion

# All applications running simultaneously without conflicts

Performance Benchmarking

// Benchmark script example:
public class PerformanceBenchmark {
    public static void main(String[] args) {
        // Test Task 2 throughput
        measurePingPongPerformance();
        
        // Test Task 3 processing speed
        measureUppercasePerformance();
        
        // Test concurrent client handling
        measureConcurrentPerformance();
    }
    
    private static void measurePingPongPerformance() {
        // Send 1000 ping messages
        // Measure average response time
        // Calculate messages per second
    }
}

Deployment Examples

Development Environment Setup

@echo off
echo Setting up Socket Programming Development Environment
echo.

echo Step 1: Compiling all applications...
call compile-all.bat

echo Step 2: Starting servers...
start "Ping-Pong Server" cmd /k "cd task2-ping-pong && java -cp src server.PingPongServer"
timeout /t 3 /nobreak >nul
start "Uppercase Server" cmd /k "cd task3-uppercase-converter && java -cp src server.UppercaseServer"

echo Step 3: Running initial tests...
echo Testing Task 1...
echo google.com | java -cp task1-hostname-converter/src HostnameToIP

echo.
echo Development environment ready!
echo - Ping-Pong Server: localhost:12345
echo - Uppercase Server: localhost:54321
echo.
echo Press any key to continue...
pause >nul

Production Deployment Simulation

// Production-like configuration example:
public class ProductionConfig {
    // Load balancing
    private static final String[] SERVER_HOSTS = {
        "server1.example.com",
        "server2.example.com", 
        "server3.example.com"
    };
    
    // High availability
    private static final int[] BACKUP_PORTS = {
        12346, 12347, 12348  // Backup ports
    };
    
    // Monitoring
    private static final boolean ENABLE_METRICS = true;
    private static final String METRICS_ENDPOINT = "/metrics";
    
    // Security
    private static final boolean REQUIRE_AUTH = true;
    private static final int MAX_CONNECTIONS = 1000;
}

Customization Examples

Protocol Extensions

Enhanced Ping-Pong Protocol

// Extended protocol supporting multiple commands:
// PING → PONG
// TIME → [current timestamp]
// ECHO <message> → <message>
// MATH <expression> → <result>

public class EnhancedPingPongServer {
    private void processMessage(String message) {
        String[] parts = message.split(" ", 2);
        String command = parts[0].toUpperCase();
        
        switch (command) {
            case "PING":
                sendResponse("PONG");
                break;
            case "TIME":
                sendResponse(new Date().toString());
                break;
            case "ECHO":
                sendResponse(parts.length > 1 ? parts[1] : "");
                break;
            // Additional commands...
        }
    }
}

Advanced Text Processing

// Enhanced uppercase converter with additional operations:
// UPPER <text> → UPPERCASE
// LOWER <text> → lowercase
// TITLE <text> → Title Case
// REVERSE <text> → txet esrever
// COUNT <text> → character count

public class AdvancedTextProcessor {
    public String processText(String input) {
        String[] parts = input.split(" ", 2);
        String operation = parts[0].toUpperCase();
        String text = parts.length > 1 ? parts[1] : "";

        return switch (operation) {
            case "UPPER" -> text.toUpperCase();
            case "LOWER" -> text.toLowerCase();
            case "TITLE" -> toTitleCase(text);
            case "REVERSE" -> new StringBuilder(text).reverse().toString();
            case "COUNT" -> String.valueOf(text.length());
            default -> text.toUpperCase(); // Default behavior
        };
    }
}

Summary

These examples demonstrate the comprehensive functionality and educational value of the socket programming assignment:

  1. Task 1 provides foundation in network programming and DNS concepts
  2. Task 2 introduces client-server architecture and protocol design
  3. Task 3 demonstrates production-quality application development

Each task builds upon previous knowledge while introducing new concepts, making this assignment suitable for:

  • Computer science education
  • Professional development
  • Technical interview preparation
  • Portfolio enhancement
  • Real-world application development

The examples show both basic usage and advanced scenarios, providing clear learning paths from beginner to expert level socket programming in Java.