WikiGalaxy

Personalize

Java Networking Features

Introduction to Java Networking

Java provides a powerful networking package, java.net, which facilitates the development of network applications. This package includes classes for creating server and client applications, handling URLs, and working with TCP/IP protocols.


import java.net.*;
public class URLDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com");
            System.out.println("Protocol: " + url.getProtocol());
            System.out.println("Host: " + url.getHost());
            System.out.println("File: " + url.getFile());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This example demonstrates how to create a URL object in Java and retrieve its components like protocol, host, and file. The URL class is a part of the java.net package and is used for representing a Uniform Resource Locator.

Console Output:

Protocol: http Host: www.example.com File:

Socket Programming

Understanding Sockets

Sockets are endpoints for communication between two machines. Java provides the Socket class for client-side and ServerSocket class for server-side communication.


import java.io.*;
import java.net.*;

public class SimpleServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(6666)) {
            Socket socket = serverSocket.accept();
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            String message = dis.readUTF();
            System.out.println("Message from client: " + message);
            dis.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This server-side socket program listens on port 6666 and waits for a client connection. Once connected, it reads a message from the client using DataInputStream.

Console Output:

Message from client: Hello Server!

DatagramSocket and DatagramPacket

Introduction to UDP Communication

Java supports UDP communication through DatagramSocket and DatagramPacket classes. These are used for sending and receiving datagram packets over the network.


import java.net.*;

public class UDPSender {
    public static void main(String[] args) {
        try {
            DatagramSocket ds = new DatagramSocket();
            String str = "Hello UDP";
            InetAddress ip = InetAddress.getByName("localhost");
            DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
            ds.send(dp);
            ds.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This example demonstrates sending a UDP packet using DatagramSocket. The DatagramPacket contains the data, the destination IP address, and the port number.

Console Output:

UDP Packet Sent

Multithreaded Server

Handling Multiple Clients

A multithreaded server can handle multiple client requests simultaneously by creating a new thread for each incoming connection.


import java.net.*;
import java.io.*;

public class MultiThreadedServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(5000)) {
            while (true) {
                Socket socket = serverSocket.accept();
                new ClientHandler(socket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ClientHandler extends Thread {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try (DataInputStream dis = new DataInputStream(socket.getInputStream())) {
            String message = dis.readUTF();
            System.out.println("Message from client: " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This multithreaded server listens on port 5000 and spawns a new thread for each client connection. The ClientHandler class handles the communication with the client.

Console Output:

Message from client: Hello Multithreaded Server!

URL Connections

Managing URL Connections

Java's URLConnection class provides methods to communicate with a URL over the network. It is used to read and write data to the server.


import java.net.*;
import java.io.*;

public class URLConnectionDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com");
            URLConnection urlConnection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This example demonstrates how to open a connection to a URL and read data from it using URLConnection and BufferedReader.

Console Output:

Example Domain ...

Secure Sockets Layer (SSL)

Implementing SSL in Java

Java provides the SSLSocket and SSLServerSocket classes to implement secure socket communication using the Secure Sockets Layer protocol.


import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;

public class SSLServer {
    public static void main(String[] args) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("keystore.jks"), "password".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, "password".toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), null, null);

        SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(8443);

        while (true) {
            SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
            sslSocket.close();
        }
    }
}
    

Example Explanation

This SSL server listens on port 8443 and uses a keystore to manage the server's private keys and certificates. It accepts secure connections and reads data from clients.

Console Output:

Secure connection established.

Non-blocking I/O with NIO

Java NIO for Networking

Java NIO (New I/O) provides non-blocking I/O operations. It includes classes like SocketChannel and ServerSocketChannel for efficient network communication.


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NonBlockingServer {
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(8080));
            serverSocketChannel.configureBlocking(false);

            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    ByteBuffer buffer = ByteBuffer.allocate(256);
                    socketChannel.read(buffer);
                    System.out.println(new String(buffer.array()).trim());
                    socketChannel.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This non-blocking server uses ServerSocketChannel to listen for incoming connections on port 8080. It reads data using a ByteBuffer and prints it to the console.

Console Output:

Hello NIO Server!

HTTP Client API

Java 11 HTTP Client

Java 11 introduced a new HTTP Client API that provides a modern and efficient way to handle HTTP requests and responses.


import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientDemo {
    public static void main(String[] args) {
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("http://www.example.com"))
                    .build();

            HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This example demonstrates how to use the Java 11 HTTP Client API to send a GET request to a URL and print the response body.

Console Output:

Example Domain ...

Network Interface

Accessing Network Interfaces

The NetworkInterface class in Java provides methods to get information about the network interfaces available on the local machine.


import java.net.*;
import java.util.*;

public class NetworkInterfaceDemo {
    public static void main(String[] args) {
        try {
            Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                System.out.println("Display name: " + ni.getDisplayName());
                System.out.println("Name: " + ni.getName());
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}
    

Example Explanation

This example lists all the network interfaces available on the local machine, displaying their names and display names.

Console Output:

Display name: lo Name: lo Display name: eth0 Name: eth0

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025