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:
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
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.netpackage). - 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).
2.2 How It Works (Step-by-Step)
- Client sends a request (e.g.,
GET /balance). - Server processes the request (e.g., queries database).
- 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 |
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
- Scalability: Handle growing users (e.g., Ncell’s 4G network during festivals).
- Reliability: Ensure uptime (e.g., NEPSE’s stock market servers).
- Security: Protect data (e.g., TLS in online banking).
- Performance: Minimize latency (e.g., low-ping for online gaming).
- 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
- Handshake: Client and server agree on encryption keys.
- Data Transfer: All messages are encrypted.
- 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 |
5.3 Real-World Use: Daraz Product Search
Client: Your browser sends
GET /search?q=laptopto 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
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.
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.
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.
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
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.
Write Working Code:
- Expect socket programs (TCP/UDP) with error handling (e.g.,
try-catchforIOException). - 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!");
- Expect socket programs (TCP/UDP) with error handling (e.g.,
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.
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").
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."
- Link concepts to apps you know:
Common Pitfalls:
- Don’t forget to close sockets (
socket.close()). - Use
BufferedReader/PrintWriterfor text-based communication (not rawInputStream). - Assume the server is running on
localhost:1234unless specified.
- Don’t forget to close sockets (
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…