Networking Basics

Networking involves the communication between multiple computing devices over a network. Java provides a robust set of classes in the java.net package to handle various network operations. Key concepts include:

  • IP Address: A unique identifier for a device on a network.
  • Port: A logical access point for communication using the Transport Layer protocols like TCP and UDP.
  • Protocol: A set of rules defining how data is transmitted over a network (e.g., HTTP, FTP, TCP, UDP).

Working with URLs

In Java, the URL class is used to represent a Uniform Resource Locator, which points to a resource on the web.

Example: Creating a URL

  import java.net.URL;

public class URLExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            System.out.println("Protocol: " + url.getProtocol());
            System.out.println("Host: " + url.getHost());
            System.out.println("Port: " + url.getPort());
            System.out.println("File: " + url.getFile());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  

Reading from a URL

  import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class URLReadExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  

Socket Programming

Socket programming is used for communication between applications running on different JREs. Java supports both TCP and UDP protocols for socket programming.

TCP Sockets

Server

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

public class TCPServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(5000)) {
            System.out.println("Server is listening on port 5000");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("New client connected");

                InputStream input = socket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));

                OutputStream output = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(output, true);

                String text;

                while ((text = reader.readLine()) != null) {
                    System.out.println("Received: " + text);
                    writer.println("Echo: " + text);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
  

Client

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

public class TCPClient {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 5000;

        try (Socket socket = new Socket(hostname, port)) {
            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output, true);

            InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));

            BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
            String text;

            while (true) {
                System.out.print("Enter message: ");
                text = consoleReader.readLine();
                writer.println(text);

                String response = reader.readLine();
                System.out.println("Server response: " + response);

                if ("bye".equalsIgnoreCase(text)) {
                    break;
                }
            }
        } catch (UnknownHostException ex) {
            System.out.println("Server not found: " + ex.getMessage());
        } catch (IOException ex) {
            System.out.println("I/O error: " + ex.getMessage());
        }
    }
}
  

UDP Sockets

Server

  import java.net.*;

public class UDPServer {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(5000);
            byte[] buffer = new byte[256];

            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);

                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                String received = new String(packet.getData(), 0, packet.getLength());

                System.out.println("Received: " + received);

                String response = "Echo: " + received;
                packet = new DatagramPacket(response.getBytes(), response.getBytes().length, address, port);
                socket.send(packet);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
  

Client

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

public class UDPClient {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket();
            InetAddress address = InetAddress.getByName("localhost");

            byte[] buffer;
            DatagramPacket packet;
            BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

            while (true) {
                System.out.print("Enter message: ");
                String message = consoleReader.readLine();
                buffer = message.getBytes();

                packet = new DatagramPacket(buffer, buffer.length, address, 5000);
                socket.send(packet);

                buffer = new byte[256];
                packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);

                String response = new String(packet.getData(), 0, packet.getLength());
                System.out.println("Server response: " + response);

                if ("bye".equalsIgnoreCase(message)) {
                    break;
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
  

Client-Server Communication

Client-server communication is a fundamental aspect of network programming. In a client-server model, the server provides resources or services, and the client requests them. Java makes it easy to implement this model using sockets.

Example: Simple Echo Server

Server

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

public class EchoServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(5000)) {
            System.out.println("Echo server is listening on port 5000");
            while (true) {
                Socket socket = serverSocket.accept();
                new EchoClientHandler(socket).start();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

class EchoClientHandler extends Thread {
    private Socket socket;

    public EchoClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try (InputStream input = socket.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(input));
             OutputStream output = socket.getOutputStream();
             PrintWriter writer = new PrintWriter(output, true)) {

            String text;
            while ((text = reader.readLine()) != null) {
                System.out.println("Received: " + text);
                writer.println("Echo: " + text);

                if ("bye".equalsIgnoreCase(text)) {
                    break;
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
  

Client

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

public class EchoClient {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 5000;

        try (Socket socket = new Socket(hostname, port)) {
            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output, true);

            InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));

            BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
            String text;

            while (true) {
                System.out.print("Enter message: ");
                text = consoleReader.readLine();
                writer.println(text);

                String response = reader.readLine();
                System.out.println("Server response: " + response);

                if ("bye".equalsIgnoreCase(text)) {
                    break;
                }
            }
        } catch (UnknownHostException ex) {
            System.out.println("Server not found: " + ex.getMessage());
        } catch (IOException ex) {
            System.out.println("I/O error: " + ex.getMessage());
        }
    }
}
  

By understanding and utilizing these concepts and tools, you can effectively manage network programming tasks in Java applications.