BIT401 Advanced Java Programming

Advanced Java ProgrammingUnit 811 min read

Socket Programming: TCP/UDP, Ports, Streams, and Client-Server Models

Unit 8 of Advanced Java Programming covers socket programming fundamentals, including TCP vs. UDP protocols, port numbers, socket creation, data streaming, and real-world client-server applications in Java. This note explains how sockets enable network communication, traces code execution, and links concepts to Nepali

Core Concepts

1. What is Socket Programming?

Socket programming is a way for Java programs to communicate over a network using TCP (Transmission Control Protocol) or UDP (User Datagram Protocol). It enables client-server or peer-to-peer interactions by exchanging data via ports and streams.

Why Use Sockets?

  • Network communication: Apps like WhatsApp (UDP for quick messages) or eSewa (TCP for secure transactions) rely on sockets.
  • Data exchange: Clients (e.g., your phone) send requests; servers (e.g., Ncell’s billing system) process and respond.
  • Flexibility: Supports both connection-oriented (TCP) and connectionless (UDP) models.

In the Real World

  1. eSewa (Nepal)

    • Uses TCP sockets for secure online payments.
    • When you pay a bill, your app (client) connects to eSewa’s server via a socket, sends encrypted data, and receives a confirmation.
    • Key idea: TCP ensures data arrives intact (reliable, ordered delivery).
  2. Pathao (Ride Allocation)

    • Uses UDP sockets for real-time driver location updates.
    • Drivers send their GPS coordinates (small, fast packets) to Pathao’s server without waiting for acknowledgments.
    • Key idea: UDP is faster but may lose packets (suitable for live updates).
  3. NTC’s Website (Nepal)

    • Uses HTTP over TCP for loading web pages.
    • When you check train schedules, your browser (client) opens a socket to NTC’s server, requests data, and displays it.
    • Key idea: Port 80 (HTTP) or 443 (HTTPS) is used by default.

2. TCP vs. UDP: Key Differences

Feature TCP UDP
Connection Connection-oriented Connectionless
Reliability Guaranteed delivery No guarantee
Speed Slower (handshakes) Faster (no overhead)
Use Case File transfers, emails Live video, gaming
Ports Requires port binding No port binding needed
Example eSewa payments Pathao driver updates

3. Ports in Socket Programming

What is a Port?

A port is a virtual endpoint for network communication. It identifies which service (e.g., HTTP, FTP) is running on a server.

  • Port numbers: Range from 0 to 65535.
    • Well-known ports: 80 (HTTP), 443 (HTTPS), 22 (SSH).
    • Dynamic ports: 1024–65535 (assigned temporarily).

Why Do We Need Ports?

  • A server can run multiple services (e.g., a web server on port 80 and an email server on port 25).
  • Clients specify the port to connect to the correct service.

4. Socket Programming Steps (TCP Example)

TCP ConnectionData: -5Response: NegativeServer (1234)Client (localhost)
TCP Client-Server Handshake and Data Flow (Port 1234)

Server-Side Steps

  1. Create a ServerSocket on a specific port.
  2. Accept a client connection (accept()).
  3. Get an InputStream/OutputStream to read/write data.
  4. Process data (e.g., check if a number is positive/negative).
  5. Close the socket when done.

Client-Side Steps

  1. Create a Socket and connect to the server’s IP/port.
  2. Get InputStream/OutputStream for communication.
  3. Send data (e.g., an integer).
  4. Receive response from the server.
  5. Close the socket.

5. Worked Example: TCP Client-Server (Positive/Negative Check)

sequenceDiagram
    participant Client
    participant Server
    Client->>Server: Connect (localhost:1234)
    Server-->>Client: Accept Connection
    Client->>Server: Send -5
    Server->>Client: Check if >= 0
    Server-->>Client: Return "Negative"
    Client->>Server: Close Socket
    Server->>Server: Close ServerSocket
Sequence Diagram of TCP Client-Server Handshake and Data Exchange
NegativeTOP
Server’s Output Stack After Sending Response (Step 3)

Server Code

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

public class NumberServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(1234); // Port 1234
        System.out.println("Server started. Waiting for client...");

        Socket clientSocket = server.accept(); // Step 1: Accept connection
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

        int number = Integer.parseInt(in.readLine()); // Read from client
        if (number >= 0) {
            out.println("Positive"); // Send response
        } else {
            out.println("Negative");
        }

        clientSocket.close(); // Step 5: Close socket
        server.close();
    }
}

Client Code

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

public class NumberClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 1234); // Connect to server
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.println(-5); // Send number to server
        String response = in.readLine(); // Read server's response
        System.out.println("Server says: " + response); // Output: "Negative"

        socket.close(); // Step 5: Close socket
    }
}

Execution Trace (Step-by-Step)

Step Server Action Client Action State After Step
1 ServerSocket created on port 1234 Socket connects to localhost:1234 Server waits; client connected.
2 accept() blocks until client connects PrintWriter sends -5 Server reads -5 from input stream.
3 Checks if -5 >= 0 → sends "Negative" BufferedReader reads "Negative" Client prints "Server says: Negative".
4 Closes clientSocket and server Closes socket Both sockets terminated.

6. UDP Socket Programming (Steps)

UDP is connectionless, so no accept() or connect() is needed. Instead:

  1. Create a DatagramSocket (no port binding required for clients).
  2. Prepare a DatagramPacket (data + IP/port).
  3. Send/Receive packets using send()/receive().
  4. Close the socket.
Packet 1Packet 2Echo: Packet 1Echo: Packet 2UDP Server (9876)Client AClient B
UDP Echo Server (Port 9876) – No Persistent Connection

Example: UDP Echo Server

import java.net.*;

public class UDPEchoServer {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(9876); // Port 9876
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        while (true) {
            socket.receive(packet); // Step 3: Wait for packet
            String received = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Received: " + received);

            // Echo back
            DatagramPacket reply = new DatagramPacket(
                packet.getData(), packet.getLength(),
                packet.getAddress(), packet.getPort()
            );
            socket.send(reply); // Step 3: Send reply
        }
    }
}

7. Common Errors and Fixes

Error Cause Solution
java.net.ConnectException Port already in use Close the server or use a different port.
SocketTimeoutException No response from server Increase timeout or check server status.
EOFException Client closed socket abruptly Handle IOException gracefully.
BindException Port not available Use serverSocket.bind(new InetSocketAddress(port)).

Exam Tip

  1. Ports are critical:

    • Always specify the port when creating a ServerSocket or Socket.
    • Example: new ServerSocket(1234) (not 0 or a random port).
  2. TCP vs. UDP:

    • TCP: Use for reliable data (e.g., file transfers, payments).
    • UDP: Use for speed (e.g., live updates, gaming).
  3. Stream handling:

    • Use BufferedReader/PrintWriter for text data.
    • For binary data, use DataInputStream/DataOutputStream.
  4. Code structure:

    • Server: ServerSocket → accept() → InputStream/OutputStream.
    • Client: Socket → connect() → InputStream/OutputStream.
  5. Real-world tie-ins:

    • eSewa: TCP for secure transactions.
    • Pathao: UDP for real-time driver tracking.
    • NTC website: HTTP (TCP) for loading pages.

Practice Question (From Past Exams)

Q: Write a UDP program where the client sends a string to the server, and the server echoes it back. Solution:

// UDP Client
DatagramSocket clientSocket = new DatagramSocket();
String message = "Hello, Server!";
byte[] sendBuffer = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, InetAddress.getByName("localhost"), 9876);
clientSocket.send(sendPacket);

// UDP Server (as shown above)

Key Steps:

  1. Client creates a DatagramPacket with data + server’s IP/port.
  2. Server receives the packet, reads the string, and sends it back.
  3. Client receives the echo and prints it.

Visual Summary

flowchart TD
    A["Client\n(Socket)"]
    B["Server\n(ServerSocket)"]
    A -->|"TCP/UDP"| C["Network\n(Internet)"]
    C --> B
    B -->|"Processes<br/>Request"| D["Response\nSent Back"]
    D --> A

In the real world

  • eSewa (Nepal) uses TCP sockets for secure transactions (e.g., bill payments). When you send money, your app (client) establishes a TCP connection to eSewa’s server (port 443 for HTTPS), encrypts the data, and waits for a confirmation response. The reliable, ordered delivery of TCP ensures no transaction is lost or corrupted.

  • Pathao (Ride Allocation) relies on UDP sockets for real-time driver location updates. Drivers send GPS coordinates as small, fast UDP packets (no handshake overhead) to Pathao’s servers. The connectionless nature of UDP allows low-latency updates, even if some packets are lost (retransmitted later).

  • NTC’s Website (Nepal) uses HTTP over TCP (port 80/443) for loading train schedules. Your browser (client) opens a TCP socket, sends an HTTP request, and receives the HTML response in a structured stream. The port binding ensures your request reaches the correct web server service.

Based on the TU BIT syllabus for Advanced Java Programming (BIT401), unit 8.

Discussion

Loading…