CACS355 Network Programming

Network ProgrammingUnit 111 min read

Client-Server Model & Network Programming Basics

Unit 1 of Network Programming: Introduces foundational concepts of network programming, the client-server model, Java’s role in networking, and design considerations for scalable network applications.

TAKEAWAYS:

  • The client-server model is the backbone of modern networking, where clients request services from centralized servers (e.g., eSewa transactions, WhatsApp messaging).
  • Java’s built-in networking libraries (e.g., Socket, ServerSocket) simplify socket programming but require understanding of TCP/UDP trade-offs.
  • Design considerations like scalability, security, and concurrency (e.g., thread pools in Pathao’s ride-matching system) directly impact real-world performance.
  • Secure sockets (e.g., TLS in Ncell’s mobile banking) encrypt data to prevent eavesdropping, a critical feature for financial apps.
  • URL/HTTP programming powers web interactions (e.g., Daraz’s product listings), requiring parsing responses like JSON/XML.
  • Exam focus: Define terms clearly, compare client-server vs. peer-to-peer, and write working socket programs with proper error handling.

1. Introduction to Network Programming

Network programming enables communication between devices over networks (LAN/WAN). Key goals:

  • Data transfer (e.g., sending a WhatsApp message).
  • Service provision (e.g., NTC’s DNS resolution for google.com).
  • Concurrency (e.g., handling 1000+ Daraz orders simultaneously).

1.1 Network Programming Paradigms

Two dominant models:

  1. Client-Server Model

    • Centralized server provides services (e.g., NEPSE stock trading).

    • Clients request resources (e.g., your laptop querying a bank’s API).

    • Visualized below:

      flowchart TD
      A["Client (e.g., eSewa App)"] -->|"Request"| B["Server (e.g., Bank Server)"]
      B -->|"Response"| A
  2. Peer-to-Peer (P2P) Model

    • Decentralized (e.g., BitTorrent file sharing).
    • Not covered in this unit (focus is client-server).

1.2 Why Java for Network Programming?

Java’s strengths:

  • Platform independence (write once, run anywhere).
  • Rich networking APIs (java.net package).
  • Multithreading support (critical for handling multiple clients).
  • Security features (e.g., SSL/TLS for secure sockets).

Comparison with Node.js:

Feature Java Node.js
Language Java (compiled) JavaScript (interpreted)
Concurrency Threads (heavyweight) Event-driven (lightweight)
Use Case Enterprise apps (banks) Real-time apps (WhatsApp)

2. Client-Server Model: Deep Dive

2.1 Definition and Components

  • Client: Initiates requests (e.g., your phone sending a payment to eSewa).
  • Server: Processes requests and returns data (e.g., eSewa’s backend server).
  • Communication Protocol: Rules for data exchange (e.g., HTTP for web, TCP for reliability).
HTTP RequestTCP ConnectionIP PacketRouted DataQueryResponse DataClientApplication LayerTransport LayerNetwork LayerServerDatabase
Data flow from client request to server response (TCP/IP model layers)

2.2 How It Works (Step-by-Step)

  1. Client sends a request (e.g., GET /balance).
  2. Server processes the request (e.g., queries database).
  3. Server sends a response (e.g., JSON: {"balance": 5000}).

Example: Pathao Ride Request

sequenceDiagram
    participant User as Client (Pathao App)
    participant Server as Pathao Server
    User->>Server: GET /find_driver?lat=27.7172&lng=85.3169
    Server->>User: {"driver_id": "A", "distance": "5 min", "eta": "10 min"}
    note over User: **Response includes driver details and estimated time**

2.3 Advantages and Disadvantages

Advantages Disadvantages
Scalable (add more servers) Single point of failure (server crash)
Centralized control Higher server maintenance cost
Efficient resource use Latency if server is overloaded
02.254.56.759Scalability9Fault Tolerance7Cost4Complexity8Relative Rating (1-10)
Client-server model trade-offs (higher = better)

Real-World Example:

  • eSewa uses client-server to validate transactions in real-time. If the server fails, users can’t complete payments (disadvantage), but scaling servers handles peak hours (advantage).

3. Design Considerations for Network Applications

3.1 Key Factors

  1. Scalability: Handle growing users (e.g., Ncell’s 4G network during festivals).
  2. Reliability: Ensure uptime (e.g., NEPSE’s stock market servers).
  3. Security: Protect data (e.g., TLS in online banking).
  4. Performance: Minimize latency (e.g., low-ping for online gaming).
  5. Concurrency: Manage multiple clients (e.g., Daraz’s order queue).

3.2 Example: Daraz’s Order Processing

  • Problem: 10,000 orders/minute during festivals.
  • Solution:
    • Load balancing: Distribute orders across servers.

    • Queue system: Use a FIFO queue to process orders in order.

    • Queue visualization:

      [Order1] → [Order2] → [Order3] → ... → [Server]
      

4. Secure Sockets

4.1 Definition

A secure socket encrypts data to prevent interception (e.g., man-in-the-middle attacks). Uses TLS/SSL (Transport Layer Security).

4.2 How It Works

  1. Handshake: Client and server agree on encryption keys.
  2. Data Transfer: All messages are encrypted.
  3. Authentication: Verifies server identity (e.g., Ncell’s mobile banking).

4.3 Example: Ncell’s Mobile Banking

  • Without security: Hackers could steal login credentials.
  • With TLS: Data is encrypted, even if intercepted.

4.4 Java Code for Secure Socket (Client)

import javax.net.ssl.*;
import java.io.*;

public class SecureClient {
    public static void main(String[] args) throws Exception {
        SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket("server.com", 8443);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Hello, secure server!");
        socket.close();
    }
}

Trace Table:

Step Action Output/State
1 Create SSL socket Socket connected to server.com:8443
2 Send encrypted "Hello" TLS handshake completes
3 Close socket Connection terminated securely

5. URL and HTTP Programming

5.1 Basics

  • URL: Uniform Resource Locator (e.g., https://www.daraz.com).
  • HTTP: Protocol for web communication (e.g., Daraz’s product pages).

5.2 Opening a URL Connection in Java

import java.net.*;
import java.io.*;

public class URLReader {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.daraz.com");
        URLConnection conn = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();
    }
}

Trace Table:

Step Action Output/State
1 Create URL object url = https://www.daraz.com
2 Open connection conn established
3 Read HTML response Prints Daraz’s homepage HTML
  • Client: Your browser sends GET /search?q=laptop to Daraz’s server.

  • Server: Returns HTML/JSON with search results.

  • HTTP Request/Response Flow:

    sequenceDiagram
        participant Client as Browser
        participant Server as Daraz Server
        Client->>Server: GET /search?q=laptop
        Server-->>Client: HTTP/200 OK + JSON results

In the Real World

  1. eSewa (Nepal)

    • Idea: Client-Server Model + Secure Sockets (TLS)
    • How: Your phone (client) sends payment requests to eSewa’s servers. TLS encrypts your card details to prevent fraud.
  2. Pathao (Ride-Hailing)

    • Idea: Concurrency (Thread Pools) + Queue Management
    • How: Pathao’s backend uses threads to handle ride requests simultaneously. A FIFO queue ensures drivers are matched fairly.
  3. NEPSE (Stock Exchange)

    • Idea: URL/HTTP Programming + Real-Time Data
    • How: Traders’ apps (clients) fetch stock prices via HTTP requests (e.g., GET /api/stocks/NEPSE). NEPSE’s servers push updates in real-time.
  4. Worked Example: Bank Loan Interest Calculation

    • Scenario: A client (you) requests a loan of ₹50,000 at 5% annual interest for 2 years.
    • Server Logic (Pseudocode):
      def calculate_interest(principal, rate, years):
          return principal * (1 + rate/100) ** years
      
    • Output: ₹55,125 (after 2 years).
    • Real-World Tie: Banks like Global IMED use similar client-server models to compute loan EMIs dynamically.

Exam Tip

  1. Define Terms Clearly:

    • For "secure socket," mention TLS/SSL encryption and handshake process.
    • For "client-server model," list components (client/server), communication flow, and advantages/disadvantages.
  2. Write Working Code:

    • Expect socket programs (TCP/UDP) with error handling (e.g., try-catch for IOException).
    • Example question: "Write a TCP client to send a message to a server." Show:
      Socket socket = new Socket("localhost", 1234);
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
      out.println("Hello Server!");
      
  3. Compare Models:

    • Always contrast client-server vs. P2P (e.g., "Client-server is scalable but has a single point of failure").
    • For Java vs. Node.js, use the table above.
  4. Visualize Flowcharts:

    • Draw sequence diagrams for client-server interactions (e.g., Pathao ride request).
    • Show state changes in sockets (e.g., "After socket.connect(), state = CONNECTED").
  5. Real-World Tie-Ins:

    • Link concepts to apps you know:
      • "eSewa uses secure sockets to encrypt transactions."
      • "Daraz’s order system uses queues to manage concurrency."
  6. Common Pitfalls:

    • Don’t forget to close sockets (socket.close()).
    • Use BufferedReader/PrintWriter for text-based communication (not raw InputStream).
    • Assume the server is running on localhost:1234 unless specified.

Final Note: Focus on code correctness and clear explanations. Examiners love seeing: ✅ Definitions with examples. ✅ Code snippets with trace tables. ✅ Real-world applications tied to theory.

Based on the TU BCA syllabus for Network Programming (CACS355), unit 1.

Discussion

Loading…