Networking
Java provides a complete set of networking APIs through the java.net package. Socket and ServerSocket for TCP client-server communication. URL and HttpURLConnection for HTTP requests. Java 11+ adds a modern HttpClient that supports HTTP/2, WebSockets, and asynchronous requests.
A Socket is a two-way communication endpoint between a client and a server. A ServerSocket listens on a specific port and accepts connections from clients. Each connection produces a new Socket that is handled in a separate thread.
HttpClient (Java 11+) is the modern replacement for HttpURLConnection — cleaner, more powerful, and supports async. It uses a builder pattern for configuration and returns a structured HttpResponse.
Java Networking APIs:
| Class | Use |
|---|---|
Socket |
TCP client connection |
ServerSocket |
TCP server listener |
URL / HttpURLConnection |
HTTP requests (legacy) |
HttpClient |
Modern HTTP (Java 11+) |
DatagramSocket |
UDP communication |
Code Example
import java.net.*;
import java.net.http.*;
import java.io.*;
import java.time.Duration;
public class NetworkingJava {
public static void main(String[] args) throws Exception {
// HTTP GET (Java 11+ HttpClient)
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Body: " + response.body().substring(0, 200));
// Simple URL fetch
URL url = new URL("https://api.ipify.org");
try (BufferedReader br = new BufferedReader(
new InputStreamReader(url.openStream()))) {
System.out.println("IP Publik: " + br.readLine());
}
// DNS lookup
InetAddress[] addresses = InetAddress.getAllByName("google.com");
for (InetAddress addr : addresses) {
System.out.println("IP: " + addr.getHostAddress());
}
}
}
Code Explanation
- HttpClient: a builder pattern for configuring timeouts, proxies, and more.
send()for synchronous requests,sendAsync()for asynchronous. - HttpRequest: the
.uri(),.header(),.GET()/.POST()methods build the request. The body handler determines the type of the response body. - HttpResponse:
statusCode()for the HTTP code (200, 404, etc.),body()for the response contents. - URL.openStream(): the old way to fetch a URL's content — enough for simple needs.
- InetAddress: DNS lookup — converts a hostname to an IP address.
Everyday Example
A simple client-server chat using Sockets:
// === SERVER ===
import java.net.*;
import java.io.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
try (ServerSocket server = new ServerSocket(5000)) {
System.out.println("Server berstreet di port 5000...");
try (Socket client = server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
String message;
while ((message = in.readLine()) != null) {
System.out.println("Client: " + message);
out.println("Server: " + message.toUpperCase());
}
}
}
}
}
// === CLIENT ===
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
Scanner sc = new Scanner(System.in)) {
System.out.println("Terhubung to server. Ketik message:");
while (sc.hasNextLine()) {
out.println(sc.nextLine());
System.out.println(in.readLine());
}
}
}
}
Summary
Java's networking APIs are very complete — from low-level Socket TCP/UDP to the modern HttpClient. For web services, use HttpClient (Java 11+) instead of the more verbose HttpURLConnection. For chat/real-time apps, Socket and ServerSocket are still relevant and effective.