Loading...

Go Back

Next page
Go Back Course Outline

Java Full Course


Networking in Java

Java Networking for Beginners <>

Java Networking for Beginners

Learn how computers communicate using Java with simple explanations and examples

What is Networking?

Networking is how computers exchange information with each other. In Java, we use special tools to:

  • Find computers (using IP addresses)
  • Connect to other computers
  • Send and receive messages

IP Addresses: Computer "Phone Numbers"

Every computer has a unique identifier called an IP address. Java's InetAddress class helps us work with these addresses.

IPLookup.java

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());
        }
    }
}

Sample Output:

My computer: MyComputer/192.168.1.5
Google: www.google.com/142.250.185.196

Client-Server Communication

Think of client-server communication like a restaurant:

Server = Restaurant (takes orders)

Client = Customer (makes requests)

Server Code (Restaurant)

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();
    }
}

Client Code (Customer)

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();
    }
}

How to run:

  1. Start the server first
  2. Then start the client

Server Output:

Restaurant open! Waiting for customers...
Customer arrived!
Customer ordered: I'd like a burger please!

Client Output:

Server says: Here's your Burger and fries

Web Communication: Talking to Websites

Java can read content from websites using the URL class:

WebPageReader.java

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());
        }
    }
}

Sample Output:

Content from example.com:
<!doctype html>
<html>
<head>
    <title>Example Domain</title>
... (website content continues)

Simple Chat Application

A basic chat program where two people can send messages to each other:

Chat Server (Post Office)

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);
        }
    }
}

Chat Client (Your Chat Program)

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);
        }
    }
}

How to use:

  1. Start the ChatServer
  2. Start two ChatClient programs
  3. Type messages in either client to chat!

Sample Chat:

// 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!

Key Networking Terms

  • IP Address - A computer's unique "phone number" (like 192.168.1.1)
  • Port - A "door number" on a computer (like apartment numbers)
  • Client - A program that requests information or services
  • Server - A program that provides information or services
  • Socket - The connection between client and server
  • Protocol - Rules for communication (like HTTP for web pages)

Common Errors & Solutions

  • Connection Refused - Server isn't running or wrong port
    Fix: Make sure server is running before client
  • Unknown Host - Wrong computer name or address
    Fix: Double-check the server address
  • Firewall Blocking - Security software blocking connection
    Fix: Check firewall settings or use different port

Java Networking Guide for Beginners | Practice these examples to master network programming

All code examples work with Java 8+

Go Back

Next page