Java Networking is a powerful feature of the Java programming language that allows developers to build applications capable of communicating over the internet or local networks. By utilizing classes from the java.net
package, programmers can create client-server applications, transfer data, and manage connections efficiently. This article presents three diverse and practical examples of Java networking to help you grasp the concepts better.
This example demonstrates how to create a simple HTTP client that fetches data from a specified URL. Such a client can be useful for web scraping, API requests, or retrieving content from the internet.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleHttpClient {
public static void main(String[] args) {
try {
String url = "https://api.github.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Content: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
This example illustrates how to create a basic TCP server that listens for incoming connections and responds to client requests. This can serve as a foundation for building applications like chat servers or file transfer services.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class BasicTcpServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server started. Listening on port 12345...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request = in.readLine();
System.out.println("Received: " + request);
out.println("Echo: " + request);
clientSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here, we will implement a simple UDP client and server to demonstrate how to send and receive messages without establishing a connection. UDP is often used for applications where speed is crucial and occasional data loss is acceptable, such as in gaming or streaming.
UDP Server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpServer {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(9876)) {
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
UDP Client:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClient {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket()) {
String message = "Hello UDP Server!";
InetAddress serverAddress = InetAddress.getByName("localhost");
DatagramPacket sendPacket = new DatagramPacket(message.getBytes(), message.length(), serverAddress, 9876);
socket.send(sendPacket);
System.out.println("Message sent: " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
}