Java Network Programming: Essential Concepts and Examples
1. Reading HTTP Headers with URLConnection
The process of reading headers using URLConnection in Java involves these steps:
- Create a
URLobject. - Open the connection using
URLConnection. - Connect to the server.
- Read header fields using methods like
getHeaderField().
import java.net.*;
public class HeaderRead {
public static void main(String[] args) throws Exception {
URL url = new URL("https://example.com");
URLConnection con = url.openConnection();
for (int i = 0; i < 10; i++) {
String header = con.getHeaderField(i);
if (header == null) break;
System.out.println(header);
}
}
}2. X-www-form URL Encoder and Decoder
X-www-form-urlencoded is used to encode data in URL format for safe transmission over the internet.
- URLEncoder: Converts special characters into URL format (e.g., space becomes
%20). - URLDecoder: Converts encoded characters back to their original form.
import java.net.*;
public class EncodeDecode {
public static void main(String[] args) throws Exception {
String encoded = URLEncoder.encode("Hello World", "UTF-8");
System.out.println(encoded);
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println(decoded);
}
}3. HTTP Keep-Alive and Cookie Policies
HTTP Keep-Alive: Keeps a TCP connection open for multiple requests, reducing the overhead of creating new connections and improving performance.
Blocking .gov Cookies
import java.net.*;
public class CookieTest {
public static void main(String[] args) {
CookieManager manager = new CookieManager();
manager.setCookiePolicy(new CookiePolicy() {
public boolean shouldAccept(URI uri, HttpCookie cookie) {
return !cookie.getDomain().contains(".gov");
}
});
CookieHandler.setDefault(manager);
}
}4. Java Secure Sockets Extension (JSSE)
JSSE is a Java API that provides secure communication using SSL and TLS protocols, offering encryption, authentication, and secure data transmission.
import javax.net.ssl.*;
public class SecureClient {
public static void main(String[] args) throws Exception {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) factory.createSocket("example.com", 443);
System.out.println("Secure connection created");
}
}5. Central Abstractions of Java NIO
Java NIO (New Input Output) provides high-performance I/O operations through these main abstractions:
- Buffer: Temporary storage for reading or writing data.
- Channel: Represents a connection to a file or network.
- Selector: Allows a single thread to manage multiple channels.
- Charset: Used for encoding and decoding characters.
6. UDP Socket Options and Port Scanning
UDP socket options (e.g., SO_TIMEOUT, SO_RCVBUF, SO_SNDBUF, SO_REUSEADDR) control the behavior of UDP communication.
import java.net.*;
public class UDPScan {
public static void main(String[] args) {
for (int port = 1024; port <= 65535; port++) {
try {
DatagramSocket ds = new DatagramSocket(port);
ds.close();
} catch (Exception e) {
System.out.println("Port in use: " + port);
}
}
}
}7. Multicast Sockets
A Multicast Group is a collection of hosts that receive the same network message simultaneously.
Working Process: Create MulticastSocket, join the group using an IP address, send/receive packets, and leave the group.
import java.net.*;
public class MulticastExample {
public static void main(String[] args) throws Exception {
MulticastSocket socket = new MulticastSocket(4446);
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.joinGroup(group);
System.out.println("Joined multicast group");
}
}8. Factory Method and Webpage Download
The Factory Method is a design pattern used to create objects without specifying the exact class.
import java.net.*;
import java.io.*;
public class DownloadPage {
public static void main(String[] args) throws Exception {
URL url = new URL("https://example.com");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}9. Socket vs. ServerSocket
| Socket | ServerSocket |
|---|---|
| Used on client side | Used on server side |
| Sends request to server | Waits for client request |
| Connects to server | Listens on port |
| Used for communication | Used to accept connections |
10. RMI and Interface Reflection
RMI Interface Example:
import java.rmi.*;
public interface Area extends Remote {
double triangle(double b, double h) throws RemoteException;
}Listing Interfaces via Reflection:
import java.lang.reflect.*;
public class ListInterfaces {
public static void main(String[] args) {
Class c = java.util.ArrayList.class;
Class[] interfaces = c.getInterfaces();
for (Class i : interfaces) {
System.out.println(i.getName());
}
}
}