WikiGalaxy

Personalize

Java Networking Basics

Understanding Sockets:

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

Client-Server Model:

The client-server model is a distributed application structure that partitions tasks between providers of a resource or service, called servers, and service requesters, called clients.


import java.net.*;
class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 8080);
            System.out.println("Connected to server");
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Server Socket Example:

This simple server listens for incoming connections and accepts them, establishing a communication link.


import java.net.*;
class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("Server started");
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected");
            clientSocket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

Connected to server

URL and URLConnection

Working with URLs:

The URL class in Java is used to represent a Uniform Resource Locator, which is a pointer to a "resource" on the World Wide Web.

Establishing URL Connections:

URLConnection is the superclass of all classes that represent a connection to a remote object referenced by a URL.


import java.net.*;
import java.io.*;
class URLExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://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();
        }
    }
}
        

Console Output:

HTML content of the page

DatagramSocket and DatagramPacket

UDP Communication:

UDP is a connectionless protocol that allows sending and receiving packets without establishing a connection.

DatagramSocket and DatagramPacket:

DatagramSocket is used to send and receive DatagramPackets over the network.


import java.net.*;
class UDPClient {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket();
            byte[] buffer = "Hello, Server".getBytes();
            InetAddress address = InetAddress.getByName("localhost");
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 9876);
            socket.send(packet);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

UDP Server Example:

This server receives a datagram packet and prints the message.


import java.net.*;
class UDPServer {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(9876);
            byte[] buffer = new byte[256];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);
            String received = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Received: " + received);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

Received: Hello, Server

Multithreaded Server

Handling Multiple Clients:

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


import java.net.*;
import java.io.*;
class MultiThreadedServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                new Thread(new ClientHandler(clientSocket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class ClientHandler implements Runnable {
    private Socket clientSocket;
    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }
    public void run() {
        try {
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            out.println("Hello, Client");
            clientSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

Hello, Client

Network Interface and InetAddress

Finding Network Interfaces:

Java's NetworkInterface class can be used to list all network interfaces available on a system.

InetAddress Class:

The InetAddress class represents an IP address and provides methods to get the local host address and other IP-related information.


import java.net.*;
import java.util.*;
class NetworkInfo {
    public static void main(String[] args) {
        try {
            Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                System.out.println("Interface: " + ni.getName());
            }
            InetAddress address = InetAddress.getLocalHost();
            System.out.println("Local Host Address: " + address.getHostAddress());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

Interface: eth0
Local Host Address: 192.168.1.5

HTTP Communication

Sending HTTP Requests:

Java provides the HttpURLConnection class to send HTTP requests and receive responses from web servers.


import java.net.*;
import java.io.*;
class HttpExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

HTML content of the page

MulticastSocket

Multicasting in Java:

Multicasting allows the transmission of a packet to multiple destinations in a single send operation. Java provides the MulticastSocket class for this purpose.


import java.net.*;
class MulticastClient {
    public static void main(String[] args) {
        try {
            MulticastSocket socket = new MulticastSocket(4446);
            InetAddress group = InetAddress.getByName("230.0.0.0");
            socket.joinGroup(group);
            byte[] buffer = new byte[256];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);
            String received = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Received: " + received);
            socket.leaveGroup(group);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

Received: Multicast message

Secure Communication with SSL

SSL in Java:

Java Secure Socket Extension (JSSE) provides a framework and implementation for a Java version of the SSL and TLS protocols.


import javax.net.ssl.*;
import java.io.*;
import java.net.*;
class SSLClient {
    public static void main(String[] args) {
        try {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket socket = (SSLSocket) factory.createSocket("localhost", 8443);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("Hello, Secure Server");
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

SSL Server Example:

This server accepts secure connections using SSL/TLS.


import javax.net.ssl.*;
import java.io.*;
import java.net.*;
class SSLServer {
    public static void main(String[] args) {
        try {
            SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
            SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(8443);
            SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println("Received: " + inputLine);
            clientSocket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

Received: Hello, Secure Server

RMI (Remote Method Invocation)

Java RMI Overview:

RMI allows an object to invoke methods on an object running in another Java Virtual Machine.


// Remote interface
import java.rmi.*;
public interface Hello extends Remote {
    String sayHello() throws RemoteException;
}

// Server implementation
import java.rmi.server.*;
public class HelloImpl extends UnicastRemoteObject implements Hello {
    public HelloImpl() throws RemoteException {}
    public String sayHello() {
        return "Hello, RMI World!";
    }
}
        

RMI Client Example:

The client looks up the remote object and invokes its method.


import java.rmi.*;
public class Client {
    public static void main(String[] args) {
        try {
            Hello stub = (Hello) Naming.lookup("rmi://localhost:5000/hello");
            System.out.println(stub.sayHello());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

Console Output:

Hello, RMI World!

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025