Networking in Java
Introduction
Java Networking allows Java programs to communicate with other computers and devices over a network.
Java provides networking classes mainly through the java.net package.
Networking can be used to build applications such as:
- Chat applications
- Client-server applications
- Online games
- Web applications
- File-sharing applications
- Network monitoring tools
Important Networking Classes
| Class / Interface | Purpose |
|---|---|
InetAddress | Represents an IP address |
Socket | Provides TCP client communication |
ServerSocket | Creates a TCP server |
DatagramSocket | Used for UDP communication |
DatagramPacket | Represents a UDP packet |
URL | Represents a web resource |
URLConnection | Provides connection to a URL |
Import Networking Package
import java.net.*;
For input and output, we may also use:
import java.io.*;
IP Address
An IP address identifies a device on a network.
Example:
192.168.1.10
Java provides the InetAddress class to work with IP addresses.
Example
import java.net.*; public class IPExample { public static void main(String[] args) throws Exception { InetAddress address = InetAddress.getByName("google.com"); System.out.println("Host Name: " + address.getHostName()); System.out.println("IP Address: " + address.getHostAddress()); } }
The IP address returned can vary depending on the network and DNS.
Client-Server Communication
Java networking commonly uses a client-server model.
Client | | Request ↓ Server | | Response ↓ Client
Client
The client requests a service from the server.
Server
The server waits for client requests and provides a service or response.
TCP Networking
TCP (Transmission Control Protocol) provides connection-oriented communication.
TCP is commonly used when reliable and ordered delivery is required.
Java provides:
Socket → Client ServerSocket → Server
TCP Server Example
import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(5000); System.out.println("Server is waiting..."); Socket socket = serverSocket.accept(); System.out.println("Client connected."); socket.close(); serverSocket.close(); } }
Explanation
new ServerSocket(5000);
Creates a server that listens on port 5000.
serverSocket.accept();
Waits for a client connection.
TCP Client Example
import java.net.*; public class Client { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 5000); System.out.println("Connected to server."); socket.close(); } }
Run the server first, then run the client.
Output
Server:
Server is waiting... Client connected.
Client:
Connected to server.
Sending Data Between Client and Server
Server
import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(5000); Socket socket = serverSocket.accept(); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Hello from Server"); socket.close(); serverSocket.close(); } }
Client
import java.net.*; import java.io.*; public class Client { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 5000); BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream())); String message = input.readLine(); System.out.println(message); socket.close(); } }
Client Output
Hello from Server
UDP Networking
UDP (User Datagram Protocol) is a connectionless communication protocol.
Java provides:
DatagramSocket DatagramPacket
UDP is commonly useful when low overhead and speed are important, while applications can tolerate some packet loss.
Basic UDP Example
import java.net.*; public class UDPExample { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(); String message = "Hello"; byte[] data = message.getBytes(); InetAddress address = InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket( data, data.length, address, 5000 ); socket.send(packet); socket.close(); } }
TCP vs UDP
| TCP | UDP |
|---|---|
| Connection-oriented | Connectionless |
| Reliable delivery | Does not guarantee delivery |
| Maintains order | Does not guarantee order |
| Generally higher overhead | Generally lower overhead |
Uses Socket and ServerSocket | Uses DatagramSocket and DatagramPacket |
| Used when reliability is important | Used when low overhead or speed is important |
URL in Java
The URL class represents a resource location on the Internet.
Example:
import java.net.*; public class URLExample { public static void main(String[] args) throws Exception { URL url = new URL("https://example.com"); System.out.println("Protocol: " + url.getProtocol()); System.out.println("Host: " + url.getHost()); System.out.println("Path: " + url.getPath()); } }
Possible output:
Protocol: https Host: example.com Path:
Port Number
A port number identifies a particular service or application endpoint on a device.
Examples:
HTTP → 80 HTTPS → 443
In Java:
ServerSocket server = new ServerSocket(5000);
Here, 5000 is the port number on which the server listens.
Advantages of Java Networking
- Supports client-server applications.
- Provides TCP and UDP communication.
- Supports communication between computers over networks.
- Provides classes for IP addresses and URLs.
- Useful for developing distributed applications.
- Supports network-based applications such as chat and file transfer systems.
Important Points
- Java networking classes are mainly provided by
java.net. InetAddressis used for IP address information.Socketis commonly used for TCP clients.ServerSocketis used to create TCP servers.DatagramSocketandDatagramPacketare used for UDP.- TCP provides reliable, ordered communication.
- UDP is connectionless and does not guarantee delivery.
- A port identifies a communication endpoint for a service.
Conclusion
Java Networking provides classes and interfaces for communication between computers and applications over a network. The most important concepts are IP addresses, ports, sockets, TCP, UDP, and client-server communication. These features make Java suitable for developing network-based and distributed applications.