CACS355 Network Programming

Network ProgrammingUnit 211 min read

TCP/UDP Sockets: Programming & Key Differences

Unit 2 of Network Programming: Explores TCP/UDP sockets—how they work, their Java implementations, real-world use cases (e.g., eSewa transactions, WhatsApp messaging), and hands-on programming with code examples, traces, and visual comparisons.

Core Concepts

Client 1 RequestClient 2 RequestClient 3 RequestFRONTREARoutin
ServerSocket's implicit queue of pending client connections (FIFO). The server processes requests in arrival order.
SYNSYN-ACKACKTOP
TCP's 3-way handshake: SYN → SYN-ACK → ACK. Each step must complete before proceeding.
TCP: SYN, SYN-ACK, ACKUDP: Fire-and-forgetTCP: Data + ACKsUDP: Data (no ACK)Client AClient BServer
Comparison of TCP handshake (3-way) vs. UDP's stateless communication. Client A uses TCP's reliable connection; Client B uses UDP's connectionless model.

1. Socket Basics

A socket is an endpoint for communication between two machines. It consists of:

  • IP address (source/destination)
  • Port number (service identifier, e.g., 80 for HTTP, 22 for SSH)

Key Idea: Sockets enable inter-process communication (IPC) over networks using protocols like TCP or UDP.


2. TCP vs. UDP: Core Differences

Feature TCP (Transmission Control Protocol) UDP (User Datagram Protocol)
Connection Connection-oriented (3-way handshake) Connectionless (fire-and-forget)
Reliability Guaranteed delivery, ordered packets, error correction No guarantees; "best-effort" delivery
Overhead High (headers + flow control) Low (minimal headers)
Speed Slower (retransmissions, acknowledgments) Faster (no handshake or retransmission)
Use Cases Email (SMTP), Web (HTTP), File Transfer (FTP), eSewa Video streaming (YouTube), VoIP (WhatsApp calls), DNS

Visual:


3. TCP Socket Programming in Java

TCP Socket: Socket clientSocket = new Socket("localhost", 12ServerSocket: ServerSocket server = new ServerSocket(1234);ClientServer
Java TCP socket connection: Client initiates connection to ServerSocket on port 1234.
Key Classes:
  • Socket: Client-side endpoint.
  • ServerSocket: Server-side endpoint (listens for connections).
  • InputStream/OutputStream: Data transfer.
Example: TCP Echo Server (Threaded)

Code:

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

public class EchoServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(12345);
        System.out.println("Server started. Waiting for connections...");

        while (true) {
            Socket clientSocket = serverSocket.accept();
            System.out.println("New client connected: " + clientSocket.getInetAddress());
            new Thread(new EchoHandler(clientSocket)).start();
        }
    }
}

class EchoHandler implements Runnable {
    private Socket clientSocket;
    public EchoHandler(Socket socket) { this.clientSocket = socket; }

    public void run() {
        try (
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)
        ) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                out.println(inputLine); // Echo back
            }
        } catch (IOException e) { e.printStackTrace(); }
        finally { try { clientSocket.close(); } catch (IOException e) {} }
    }
}

Trace Table (Server handles 2 clients):

Step Client 1 Action Server State Client 2 Action
1 Connects to port 12345 ServerSocket accepts connection; new EchoHandler thread starts. —
2 Sends "Hello" Thread reads "Hello", echoes back. —
3 Disconnects Thread closes clientSocket; loop continues for next client. Connects to port 12345

Why Threads?

  • Advantage: Handles multiple clients concurrently (scalable).
  • Disadvantage: Thread management overhead.

4. UDP Socket Programming in Java

UDP DatagramPacket: send(data, address, port);UDP DatagramSocket: receive(buffer, address, port);ClientServer
Java UDP socket communication: Client sends datagram packets to Server without handshake.
Key Classes:
  • DatagramSocket: UDP endpoint.
  • DatagramPacket: Wraps data + metadata (IP, port).
Example: UDP Port Scanner (1024–2000)

Code:

import java.net.*;

public class UDPScanner {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(100); // Timeout for faster scanning

        for (int port = 1024; port <= 2000; port++) {
            try {
                DatagramPacket packet = new DatagramPacket(
                    new byte[0], 0, InetAddress.getByName("localhost"), port
                );
                socket.send(packet); // Send empty packet
                System.out.println("Port " + port + " is open");
            } catch (SocketTimeoutException e) {
                System.out.println("Port " + port + " is closed");
            }
        }
        socket.close();
    }
}

Output Example:

Port 1024 is closed
Port 1025 is open  <-- e.g., XMPP service
Port 1026 is closed
...

Real-World Tie:

  • eSewa’s Payment Gateway: Uses TCP for secure transaction confirmation (reliable delivery of payment status).
  • WhatsApp Voice Calls: Uses UDP for real-time audio (speed > reliability).

5. Secure Sockets (SSL/TLS)

A secure socket encrypts data using SSL/TLS (e.g., HTTPS). Java’s SSLSocket extends Socket:

import javax.net.ssl.*;

```figure
{"type":"tree","root":{"v":"SSL/TLS Handshake","children":[{"v":"Client Hello","children":[{"v":"Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"},{"v":"Key Exchange: Ephemeral Diffie-Hellman"}]},{"v":"Server Hello","children":[{"v":"Certificate: eSewa’s Root CA"},{"v":"Encrypted Pre-Master Secret"}]},{"v":"Finished","children":[{"v":"Symmetric Keys: AES-256"},{"v":"Integrity Check: HMAC-SHA256"}]}]},"caption":"SSL/TLS handshake tree: Client and server agree on encryption (e.g., AES-256) and authenticate via certificates (e.g., eSewa’s CA)."}

SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket socket = (SSLSocket) factory.createSocket("tufoshss.edu.np", 443); Why?

  • Prevents man-in-the-middle attacks (e.g., intercepting eSewa login credentials).

6. Practical Applications

Company/Product Protocol Used Why?
eSewa TCP Reliable transaction confirmation (no lost payments).
WhatsApp Calls UDP Low-latency voice/data (real-time, not critical if packets drop).
Daraz Order Queue TCP Ordered delivery of orders (no duplicates or lost orders).
NTC’s DNS UDP Fast domain resolution (DNS queries tolerate some packet loss).

7. Key Comparisons

TCP vs. UDP: When to Use?
Scenario Protocol Reason
File transfer (FTP) TCP Ensures complete file delivery.
Video streaming (YouTube) UDP Prioritizes speed over perfection (buffering handles lost packets).
Online banking (eSewa) TCP Critical data (money) must arrive intact.
IoT sensor data UDP Sensors send periodic updates; occasional loss is acceptable.

In the Real World

  1. eSewa’s Transaction Flow:

    • TCP ensures the bank’s server confirms your payment before deducting money from your account.
    • Worked Example: If your eSewa app sends a payment request but the server doesn’t ACK, it retries (TCP’s reliability).
  2. WhatsApp Voice Calls:

    • Uses UDP to send voice packets every 20ms. If a packet is lost, the app buffers and replays the last clear audio (no noticeable lag).
  3. Daraz’s Order Queue:

    • Orders are processed in FIFO order (like a TCP stream). If an order is lost mid-transmission, Daraz’s system detects it via retries (TCP’s built-in error recovery).

Exam Tip

  • Focus Areas:

    1. Define and differentiate TCP/UDP (table format scores high).
    2. Code snippets: Always include a Socket/ServerSocket example with threading (for TCP) or DatagramPacket (for UDP).
    3. Real-world mapping: Link protocols to apps (e.g., "eSewa uses TCP for reliability").
    4. Secure sockets: Mention SSLSocket and its role in encryption (e.g., HTTPS).
    5. Port scanning: Know how to scan UDP ports (like in the scanner example above).
  • Common Pitfalls:

    • Forgetting to close sockets (leaks resources).
    • Mixing TCP/UDP use cases (e.g., using UDP for banking—wrong!).
    • Not handling exceptions (e.g., SocketTimeoutException in UDP).
  • High-Scoring Answers:

    • Compare TCP/UDP with a table + 2 real-world examples.
    • Threaded TCP server code + trace table (shows scalability).
    • UDP port scanner code + output snippet (demonstrates practical use).

Visual Recap

  1. TCP 3-Way Handshake:
sequenceDiagram
    participant Client
    participant Server
    Client->>Server: SYN (Connection Request)
    Server->>Client: SYN-ACK (Agreement + ACK)
    Client->>Server: ACK (Final Confirmation)
    Client->>Server: Data
    Server->>Client: ACK
    note right of Client: TCP Reliable Data Transfer
    Client->>Server: SYN
    Server->>Client: SYN-ACK
    Client->>Server: ACK
    note right of Client: UDP Fire-and-Forget
    Client->>Server: Data
    Server->>Client: Data (no ACK)
  1. UDP Packet Structure:

    +---------------------+
    |     UDP Header      |
    +---------+-----------+
    | Source | Destination|
    | Port   | Port       |
    +---------+-----------+
    |         Data        |
    +---------------------+
    
  2. TCP vs. UDP Headers:

    Field TCP (20 bytes) UDP (8 bytes)
    Source Port Yes Yes
    Destination Port Yes Yes
    Sequence # Yes (for ordering) No
    Acknowledgment Yes (for reliability) No
    Checksum Yes Yes
    Urgent Yes No

Final Note: Always visualize sockets as connections (TCP) or datagrams (UDP) and trace their state changes step-by-step in exams. Use code snippets to show hands-on understanding.

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

Discussion

Loading…