⬅ Previous Next ➡

Java Networking

Java Networking Fundamentals: Sockets, Client-Server, URL, HttpURLConnection & Networking APIs
  • Networking means communication between computers/devices to share data.
  • Java networking is mainly provided by java.net package (Socket, ServerSocket, URL, HttpURLConnection).
  • Two common models: TCP (reliable connection) and UDP (faster, no guarantee).

1) Sockets (TCP) Basics

  • Socket is an endpoint for communication between two machines.
  • ServerSocket waits for client connections.
  • Socket is used by client to connect to server.
  • TCP is connection-oriented and reliable.

2) Server-Client Communication (TCP Example)

  • Server listens on a port (e.g., 5000).
  • Client connects using IP/host + port.
  • Data can be sent using streams (InputStream/OutputStream).
// Server.java
import java.io.*;
import java.net.*;

class Server {
    public static void main(String[] args) {
        try (ServerSocket server = new ServerSocket(5000)) {
            System.out.println("Server started on port 5000...");

            Socket client = server.accept();
            System.out.println("Client connected: " + client.getInetAddress());

            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream(), true);

            String msg = in.readLine();
            System.out.println("Client says: " + msg);

            out.println("Hello from Server! Received: " + msg);

            client.close();
        } catch (Exception e) {
            System.out.println("Server error: " + e.getMessage());
        }
    }
}
// Client.java
import java.io.*;
import java.net.*;

class Client {
    public static void main(String[] args) {
        try (Socket s = new Socket("localhost", 5000)) {

            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter out = new PrintWriter(s.getOutputStream(), true);

            out.println("Hi Server, I"m Sourav\");

            String reply = in.readLine();
            System.out.println("Server replied: " + reply);

        } catch (Exception e) {
            System.out.println("Client error: " + e.getMessage());
        }
    }
}

3) URL Handling (java.net.URL)

  • URL represents a web address.
  • Useful methods: getProtocol(), getHost(), getPath(), getQuery(), openStream().
import java.net.URL;

class UrlDemo {
    public static void main(String[] args) {
        try {
            URL u = new URL("https://example.com/path/page?x=1");

            System.out.println("Protocol: " + u.getProtocol());
            System.out.println("Host: " + u.getHost());
            System.out.println("Path: " + u.getPath());
            System.out.println("Query: " + u.getQuery());
        } catch (Exception e) {
            System.out.println("URL error: " + e.getMessage());
        }
    }
}

4) HttpURLConnection (GET Request)

  • HttpURLConnection is used to send HTTP requests (GET/POST).
  • Common steps:
    • Create URL
    • Open connection
    • Set request method
    • Read response using InputStream
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

class HttpGetDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://example.com");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            con.setRequestMethod("GET");
            con.setConnectTimeout(5000);
            con.setReadTimeout(5000);

            int code = con.getResponseCode();
            System.out.println("Response Code: " + code);

            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
            con.disconnect();

        } catch (Exception e) {
            System.out.println("HTTP error: " + e.getMessage());
        }
    }
}

5) HttpURLConnection (POST Request - Basic)

  • For POST, set doOutput(true) and write data using OutputStream.
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

class HttpPostDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://example.com/api");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            String data = "name=Sourav&course=Java";

            try (OutputStream os = con.getOutputStream()) {
                os.write(data.getBytes());
            }

            System.out.println("Response Code: " + con.getResponseCode());
            con.disconnect();

        } catch (Exception e) {
            System.out.println("POST error: " + e.getMessage());
        }
    }
}

6) Common Java Networking APIs (java.net)

  • InetAddress: IP address/host information.
  • Socket: client-side TCP connection.
  • ServerSocket: server-side TCP listener.
  • DatagramSocket, DatagramPacket: UDP communication.
  • URL, URLConnection, HttpURLConnection: web URL + HTTP requests.
import java.net.InetAddress;

class InetDemo {
    public static void main(String[] args) {
        try {
            InetAddress ip = InetAddress.getLocalHost();
            System.out.println("Host: " + ip.getHostName());
            System.out.println("IP: " + ip.getHostAddress());
        } catch (Exception e) {
            System.out.println("InetAddress error: " + e.getMessage());
        }
    }
}

7) Quick Notes

  • TCP Socket = reliable communication (client-server).
  • Always close sockets/streams (use try-with-resources).
  • HttpURLConnection is classic way for HTTP; modern apps may also use HttpClient (Java 11+).
  • Use timeouts to avoid hanging network calls.
⬅ Previous Next ➡