Learn how computers communicate using Java with simple explanations and examples
Networking is how computers exchange information with each other. In Java, we use special tools to:
Every computer has a unique identifier called an IP address. Java's InetAddress
class helps us work with these addresses.
import java.net.InetAddress; public class IPLookup { public static void main(String[] args) { try { // Find your own computer's address InetAddress myComputer = InetAddress.getLocalHost(); System.out.println("My computer: " + myComputer); // Find Google's address InetAddress google = InetAddress.getByName("www.google.com"); System.out.println("Google: " + google); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
My computer: MyComputer/192.168.1.5 Google: www.google.com/142.250.185.196
Think of client-server communication like a restaurant:
Server = Restaurant (takes orders)
Client = Customer (makes requests)
import java.net.*; import java.io.*; public class RestaurantServer { public static void main(String[] args) throws IOException { // Open the restaurant (create server socket) ServerSocket server = new ServerSocket(1234); System.out.println("Restaurant open! Waiting for customers..."); // Wait for a customer (client) Socket customer = server.accept(); System.out.println("Customer arrived!"); // Get the order (read from client) BufferedReader orderReader = new BufferedReader( new InputStreamReader(customer.getInputStream())); String order = orderReader.readLine(); System.out.println("Customer ordered: " + order); // Prepare the food (process request) String food = "Burger and fries"; // Serve the food (send response) PrintWriter foodWriter = new PrintWriter(customer.getOutputStream(), true); foodWriter.println("Here's your " + food); // Close connections customer.close(); server.close(); } }
import java.net.*; import java.io.*; public class RestaurantCustomer { public static void main(String[] args) throws IOException { // Go to the restaurant (connect to server) Socket restaurant = new Socket("localhost", 1234); // Place an order (send request) PrintWriter orderWriter = new PrintWriter(restaurant.getOutputStream(), true); orderWriter.println("I'd like a burger please!"); // Wait for food (read response) BufferedReader foodReader = new BufferedReader( new InputStreamReader(restaurant.getInputStream())); String food = foodReader.readLine(); System.out.println("Server says: " + food); // Leave restaurant (close connection) restaurant.close(); } }
Restaurant open! Waiting for customers... Customer arrived! Customer ordered: I'd like a burger please!
Server says: Here's your Burger and fries
Java can read content from websites using the URL
class:
import java.net.*; import java.io.*; public class WebPageReader { public static void main(String[] args) { try { // Create a URL object (like an address) URL webpage = new URL("https://example.com"); // Open connection to the website BufferedReader reader = new BufferedReader( new InputStreamReader(webpage.openStream())); // Read the webpage content String line; System.out.println("Content from example.com:"); while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
Content from example.com: <!doctype html> <html> <head> <title>Example Domain</title> ... (website content continues)
A basic chat program where two people can send messages to each other:
import java.net.*; import java.io.*; public class ChatServer { public static void main(String[] args) throws IOException { ServerSocket postOffice = new ServerSocket(5555); System.out.println("Chat Server started! Waiting for friends to connect..."); // Wait for first friend Socket friend1 = postOffice.accept(); System.out.println("Friend 1 connected!"); // Wait for second friend Socket friend2 = postOffice.accept(); System.out.println("Friend 2 connected! Chat starting..."); // Create streams for both friends BufferedReader in1 = new BufferedReader( new InputStreamReader(friend1.getInputStream())); PrintWriter out1 = new PrintWriter(friend1.getOutputStream(), true); BufferedReader in2 = new BufferedReader( new InputStreamReader(friend2.getInputStream())); PrintWriter out2 = new PrintWriter(friend2.getOutputStream(), true); // Tell both friends they're connected out1.println("You're connected to Friend 2!"); out2.println("You're connected to Friend 1!"); // Chat loop while (true) { // Friend 1 sends message to Friend 2 if (in1.ready()) { String message = in1.readLine(); out2.println("Friend 1: " + message); } // Friend 2 sends message to Friend 1 if (in2.ready()) { String message = in2.readLine(); out1.println("Friend 2: " + message); } // Small delay to prevent high CPU usage Thread.sleep(100); } } }
import java.net.*; import java.io.*; import java.util.Scanner; public class ChatClient { public static void main(String[] args) throws IOException { // Connect to the chat server Socket chatServer = new Socket("localhost", 5555); System.out.println("Connected to chat server!"); // Create thread to read messages new Thread(() -> { try { BufferedReader in = new BufferedReader( new InputStreamReader(chatServer.getInputStream())); String message; while ((message = in.readLine()) != null) { System.out.println(message); } } catch (IOException e) { System.out.println("Disconnected from server"); } }).start(); // Create writer to send messages PrintWriter out = new PrintWriter(chatServer.getOutputStream(), true); Scanner scanner = new Scanner(System.in); // Read user input and send messages while (true) { String message = scanner.nextLine(); out.println(message); } } }
// Friend 1's screen: Connected to chat server! You're connected to Friend 2! Friend 2: Hello! Friend 2: How are you? // Friend 2's screen: Connected to chat server! You're connected to Friend 1! Friend 1: Hi there! Friend 1: I'm doing great!