5 Network Programming

Advanced Java Programming · Unit 5 · 5 hrs

Network Programming

Exam-focused notes for Network Programming (Advanced Java Programming, CSC419): what the TU syllabus asks and how it has actually been tested, with 3 solved past questions from this unit.

Network Programming in short

This unit covers network programming in Java: the transport protocols sockets are built on, how to write TCP and UDP client-server programs, how to work with URLs, and how to send mail through the JavaMail API.

Network Programming: notes

Transmission Control Protocol (TCP), User Datagram Protocol (UDP), Ports, IP Address Network Classes in JDK

Network programming (also called socket programming) writes programs that run on separate, networked machines and communicate with each other. The java.net package supports the two standard transport protocols, TCP and UDP.

TCP (Transmission Control Protocol) is a transport layer protocol, always paired with IP as "TCP/IP". The sending side breaks application data into numbered packets, transmits them, and the receiving side reassembles them in order before handing the data back up to the application layer. Its defining properties are: it is connection-oriented (a connection is established and held open for the duration of the exchange), reliable (lost packets are retransmitted), ordered (packets are reassembled in the sequence they were sent, even if they arrive out of order), full duplex (both ends can send at once), and stream-oriented.

UDP (User Datagram Protocol) sends independent packets called datagrams from one machine to another with no guarantee that they arrive, arrive in order, or arrive only once; it is connectionless.

TCPUDP
ConnectionConnection-orientedConnectionless
SpeedSlower (more overhead)Faster
HandshakeUses a handshake to establish the connectionNo handshake
ReliabilityReliable; retransmits lost dataUnreliable; simply discards a damaged packet
AcknowledgementUses acknowledgement segmentsNo acknowledgements
WeightHeavyweightLightweight
Typical useWeb browsing, file transfer, email; anything needing every byte to arrive correctly and in orderStreaming media, VoIP, online games; anything where an occasional dropped packet matters less than low latency

A port is a 16-bit unsigned number (0 to 65535) that identifies a specific application or service on a machine, alongside its IP address; because a single client may have several connections open at once (an email client and a game, for instance), the IP address alone is not enough to route data to the right application, and the transport layer uses the port number to complete that addressing, for example 192.168.1.100:7.

The java.net package provides the core classes used for network programming: Socket creates a client-side connection using TCP; ServerSocket accepts incoming TCP connections on the server side; InetAddress represents an IP address; DatagramSocket sends and receives UDP packets; DatagramPacket represents a single UDP packet, holding both its data and its destination address and port; URL represents a Uniform Resource Locator, pointing to a resource on the web; and URLConnection represents an active communication link between a URL and the application using it.

A socket is one endpoint of a two-way link between two programs on a network, bound to a port so that TCP can deliver incoming data to the right application.

What this unit covers

  • Transmission control Protocol (TCP), User Datagram Protocol (UDP), Ports, IP Address Network Classes in JDK
  • Socket programming using TCP, Socket programming using UDP, Working with URL's, Working with URL Connection Class
  • Java Mail API, Sending and Receiving Email

Socket programming using TCP, Socket programming using UDP, Working with URL's, Working with URL Connection Class

2081 · 10 marks

What is the task of the Listener interface? Write a socket program for a file server that makes a collection of files available for transmission to clients. When a client connects to the server, the server first reads a one-line command from the client. The command string can be of the form 'GET ', where is a file name. The server checks whether the requested file actually exists. If so, it first sends the word 'OK' as a message to the client. Then it sends the contents of the file and closes the connection. Otherwise, it sends 'ERROR' to the client as message and closes the connection. Assume that there is no sub directories.[10]

Show solved answer

Listener Interface and File Server Socket Program

Part 1: Task of the Listener Interface

The Listener interface (specifically ServerSocket in Java TCP socket programming) is responsible for listening for incoming client connection requests on a specified port number.

Key Tasks of the Listener (ServerSocket):

  • It waits and listens on a specific port for any client attempting to make a connection.
  • When a client request arrives, it accepts the connection using the accept() method, which returns a Socket object representing the client connection.
  • It acts as the entry point for the server side of a TCP connection.
  • It allows the server to communicate with multiple clients by repeatedly calling accept().
  • It manages the binding of the server to a port so clients know where to connect.

In Java, the typical usage is:

ServerSocket ss = new ServerSocket(portNumber);
Socket cs = ss.accept(); // blocks until a client connects

Part 2: File Server Socket Program

Design Logic (Step by Step):

  1. Server creates a ServerSocket and listens on a port.
  2. Client connects and sends a command like GET filename.txt.
  3. Server parses the command and extracts the filename.
  4. Server checks if the file exists in the current directory.
  5. If file exists: sends OK, then sends file contents line by line, then closes.
  6. If file does not exist: sends ERROR, then closes.

Server Program: FileServer.java

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

public class FileServer {
    public static void main(String[] args) throws IOException {

        // Step 1: Create ServerSocket and listen on port 1254
        ServerSocket ss = new ServerSocket(1254);
        System.out.println("File Server started. Waiting for clients...");

        // Step 2: Keep server running to accept multiple clients
        while (true) {
            // Step 3: Accept incoming client connection
            Socket cs = ss.accept();
            System.out.println("Client connected: " + cs.getInetAddress());

            // Step 4: Get input and output streams
            BufferedReader in = new BufferedReader(
                new InputStreamReader(cs.getInputStream())
            );
            PrintWriter out = new PrintWriter(cs.getOutputStream(), true);

            // Step 5: Read the command sent by client (e.g., "GET filename.txt")
            String command = in.readLine();
            System.out.println("Command received: " + command);

            // Step 6: Parse the command
            if (command != null && command.startsWith("GET ")) {

                // Extract filename from command
                String filename = command.substring(4).trim();

                // Step 7: Check if file exists (no subdirectories assumed)
                File file = new File(filename);

                if (file.exists() && file.isFile()) {
                    // Step 8a: File found - send OK
                    out.println("OK");
                    System.out.println("Sending file: " + filename);

                    // Step 9: Read file and send contents line by line
                    BufferedReader fileReader = new BufferedReader(
                        new FileReader(file)
                    );
                    String line;
                    while ((line = fileReader.readLine()) != null) {
                        out.println(line);
                    }
                    fileReader.close();
                    System.out.println("File sent successfully.");

                } else {
                    // Step 8b: File not found - send ERROR
                    out.println("ERROR");
                    System.out.println("File not found: " + filename);
                }

            } else {
                // Invalid command format
                out.println("ERROR");
                System.out.println("Invalid command received.");
            }

            // Step 10: Close streams and connection
            in.close();
            out.close();
            cs.close();
            System.out.println("Connection closed.");
        }
    }
}

Client Program: FileClient.java

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

public class FileClient {
    public static void main(String[] args) throws IOException {

        // Step 1: Open a socket to connect to the server
        Socket cs = new Socket("localhost", 1254);

        // Step 2: Open input and output streams
        BufferedReader in = new BufferedReader(
            new InputStreamReader(cs.getInputStream())
        );
        PrintWriter out = new PrintWriter(cs.getOutputStream(), true);

        // Step 3: Send GET command to the server
        String filename = "hello.txt"; // filename to request
        out.println("GET " + filename);
        System.out.println("Request sent: GET " + filename);

        // Step 4: Read the server's first response (OK or ERROR)
        String response = in.readLine();
        System.out.println("Server Response: " + response);

        if (response != null && response.equals("OK")) {
            // Step 5: Read and display the file contents
            System.out.println("--- File Contents ---");
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            System.out.println("--- End of File ---");

        } else {
            // File not found on server
            System.out.println("Requested file does not exist on server.");
        }

        // Step 6: Close streams and socket
        in.close();
        out.close();
        cs.close();
    }
}

Sample Output

When hello.txt exists on server:

Server side:

File Server started. Waiting for clients...
Client connected: /127.0.0.1
Command received: GET hello.txt
Sending file: hello.txt
File sent successfully.
Connection closed.

Client side:

Request sent: GET hello.txt
Server Response: OK
--- File Contents ---
Hello, this is a test file.
Welcome to File Server.
--- End of File ---

When missing.txt does NOT exist:

Client side:

Request sent: GET missing.txt
Server Response: ERROR
Requested file does not exist on server.

Server side:

Client connected: /127.0.0.1
Command received: GET missing.txt
File not found: missing.txt
Connection closed.

Explanation of the Key Classes and Methods

Class or MethodRole in the Program
ServerSocket(1254)The listener: binds the server to port 1254 and waits for connection requests
accept()Blocks until a client connects, then returns a Socket for that one client
Socket("localhost", 1254)The client end: opens a TCP connection to the server's listening port
getInputStream() and getOutputStream()Give the byte streams of the connection, wrapped here in a BufferedReader and a PrintWriter
PrintWriter(..., true)The true turns on auto flush, so OK, ERROR and each line of the file leave the socket immediately
readLine()Reads one line of the command from the client, and on the client side reads the response and the file
File.exists() and File.isFile()Confirm that the requested name refers to an existing ordinary file in the current directory
close()Releases the streams and tears the connection down, which also signals end of file to the client

The protocol works because the client knows how to interpret what it reads. The first line is always the status word, so the client reads exactly one line, compares it with OK, and only then treats every remaining line up to end of stream as file content. Closing the socket on the server is what makes the client's readLine() return null and end the loop, so no explicit length or terminator has to be sent.

Limitations and Possible Improvements

The server handles one client at a time, because the whole exchange happens inside the accept() loop; wrapping the per client code in a Thread (or handing it to a thread pool) lets several clients be served concurrently. Reading with FileReader and writing with PrintWriter also assumes a text file, so a binary file such as an image would be corrupted; using FileInputStream with OutputStream.write() on a byte buffer transfers any file type unchanged. Finally, the file name arrives from the network and is used as it stands, so a name containing a path such as ../secret.txt would escape the intended folder; the question assumes there are no subdirectories, but a real server should reject any name containing a separator before opening it.

Open this answer on its own page →

2076 · 5 marks

Write Java programs using TCP sockets that communicate with each other in a computer network. [5]

A socket is one endpoint of a two-way communication link between two programs running on the network. It is bound to a port number so that the TCP layer can identify the application data to be sent to the destination. The java.net package provides support for TCP socket programming in Java. --- 1...

Open this answer on its own page →

Java Mail API, Sending and Receiving Email

2078 · 5 marks

What is Java Mail API? How can you use this API to send email messages? [5]

The JavaMail API is an API used to compose, write, and read electronic messages (emails). It provides a protocol-independent and platform-independent framework for sending and receiving emails. The core classes of JavaMail API are found in the java.mail and java.mail.activation packages. Note on ...

Open this answer on its own page →