Networking in Java

Networking in Java is all about enabling communication between applications or devices over a network, typically using TCP/IP protocols. Java provides a rich set of APIs in the java.net package to handle networking. Let’s break it down step by step.


1. Key Classes in java.net

ClassPurpose
SocketRepresents a client-side TCP connection.
ServerSocketListens for incoming TCP connections on the server side.
InetAddressRepresents IP addresses and hostnames.
URLRepresents a Uniform Resource Locator (for HTTP, FTP, etc.).
URLConnectionProvides communication between Java and a URL resource.
DatagramSocketUsed for sending/receiving UDP packets.
DatagramPacketRepresents data to send or receive over UDP.

2. TCP Networking (Connection-Oriented)

TCP ensures reliable communication. A typical client-server model:

Server Example

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

public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(5000);
        System.out.println("Server is listening on port 5000...");
        
        Socket socket = serverSocket.accept(); // Wait for a client
        System.out.println("Client connected.");

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        String message = in.readLine();
        System.out.println("Received from client: " + message);
        out.println("Hello Client! Message received.");

        socket.close();
        serverSocket.close();
    }
}

Client Example

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

public class TCPClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 5000);
        
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.println("Hello Server!");
        System.out.println("Server says: " + in.readLine());

        socket.close();
    }
}

3. UDP Networking (Connectionless)

UDP is faster but does not guarantee delivery.

Server Example

import java.net.*;

public class UDPServer {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(9876);
        byte[] receiveData = new byte[1024];

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        socket.receive(receivePacket);

        String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
        System.out.println("Received: " + message);

        socket.close();
    }
}

Client Example

import java.net.*;

public class UDPClient {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();
        InetAddress address = InetAddress.getByName("localhost");

        String message = "Hello UDP Server!";
        byte[] sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, 9876);
        socket.send(sendPacket);

        socket.close();
    }
}

4. Working with URLs

Java makes it easy to work with web resources:

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

public class URLExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.example.com");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        in.close();
    }
}

5. Things to Remember

  • TCP → reliable, connection-oriented, slower.
  • UDP → faster, connectionless, no guarantee of delivery.
  • Socket → client side TCP.
  • ServerSocket → server side TCP.
  • DatagramSocket & DatagramPacket → UDP communication.
  • Always close your sockets and streams to avoid resource leaks.

Leave a Reply