Java
Module 27: Java NetworkingBeginner22 min read

Networking, HttpClient & Socket Programming

Understand TCP vs UDP, inspect URLs and InetAddress, and build client-server communication with Sockets and Java 11+ HttpClient.

Key Takeaways & Core Concepts
  • TCP (`Socket` / `ServerSocket`): Connection-oriented, reliable, ordered byte stream—used by HTTP, databases, and chat servers.
  • UDP (`DatagramSocket` / `DatagramPacket`): Connectionless, low-overhead packets—used by DNS, gaming, and live video streaming.
  • `java.net.http.HttpClient` (Java 11+): Replaces the verbose HttpURLConnection with HTTP/2 multiplexing, WebSockets, and non-blocking sendAsync() returning CompletableFuture<HttpResponse<T>>.
  • `URI` vs `URL`: Prefer URI for parsing and validation (new URL(string) was deprecated in Java 20).

Introduction

Java's networking stack spans high-level HTTP clients (java.net.http.HttpClient) down to low-level TCP/UDP sockets (java.net.Socket, ServerSocket, DatagramSocket).

Parsing URIs & Building an HTTP Request Spec
1import java.net.URI;
2
3public class Main {
4 public static void main(String[] args) {
5 URI uri = URI.create("https://codezov.com:443/tutorials/java");
6 System.out.println("Scheme: " + uri.getScheme());
7 System.out.println("Host: " + uri.getHost());
8 System.out.println("Port: " + uri.getPort());
9 System.out.println("Path: " + uri.getPath());
10 }
11}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
11 lines
Note: `URI.create(...)` validates syntax without throwing a checked exception.

TCP vs UDP & Core Classes

  • TCP (`Socket` / `ServerSocket`): Connection-oriented, reliable, ordered byte stream—used by HTTP, databases, and chat servers.
  • UDP (`DatagramSocket` / `DatagramPacket`): Connectionless, low-overhead packets—used by DNS, gaming, and live video streaming.
  • `java.net.http.HttpClient` (Java 11+): Replaces the verbose HttpURLConnection with HTTP/2 multiplexing, WebSockets, and non-blocking sendAsync() returning CompletableFuture<HttpResponse<T>>.
  • `URI` vs `URL`: Prefer URI for parsing and validation (new URL(string) was deprecated in Java 20).
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)