Java Programming Notes
Module 7: Networking and Advanced
7.1 Networking Fundamentals
Introduction
Computer networking allows multiple devices to communicate and share data over a network. In
Java, networking is primarily handled using the [Link] package.
Enables communication between computers
Used in web applications, distributed systems, and APIs
Based on protocols like TCP and UDP
IP Address
An IP address is a unique identier assigned to each device on a network.
IPv4: 32-bit address (e.g., [Link])
IPv6: 128-bit address (e.g., 2001:db8::1)
It helps identify the device and its location in the network.
Port Numbers
Ports are communication endpoints used to identify specic services on a device.
Range: 0 to 65535
Well-known ports (01023): HTTP (80), HTTPS (443)
Registered ports (102449151)
Dynamic ports (4915265535)
TCP vs UDP
TCP (Transmission Control Protocol)
Connection-oriented
Reliable and ordered delivery
Slower due to error checking
UDP (User Datagram Protocol)
Connectionless
Faster but unreliable
No guarantee of delivery
1
Connection Types
Connection-Oriented
Requires connection setup
Example: TCP
Connectionless
No connection required
Example: UDP
Streams in Networking
Streams are used for data transmission.
InputStream Reads data
OutputStream Writes data
Example: Simple Stream Usage
import [Link].*;
class StreamDemo {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("[Link]");
FileOutputStream out = new FileOutputStream("[Link]");
int data;
while((data = [Link]()) != -1) {
[Link](data);
}
[Link]();
[Link]();
}
}
Output:
File copied successfully
Important Points
IP address identies device
Port identies application
TCP is reliable, UDP is fast
Streams are used for communication
2
7.2 Java Networking Basics ([Link] Package)
Introduction
Java provides networking capabilities through the [Link] package. It allows applications to com-
municate over networks using TCP and UDP protocols.
Provides classes for networking operations
Supports both client and server communication
Used for building distributed applications
Important Classes in [Link]
InetAddress
Socket
ServerSocket
URL
URLConnection
InetAddress
Represents IP address of a host
Used to get host information
Example:
import [Link].*;
class Demo {
public static void main(String[] args) throws Exception {
InetAddress ip = [Link]("[Link]");
[Link]("Host Name: " + [Link]());
[Link]("IP Address: " + [Link]());
}
}
Socket (Client)
A Socket is used to connect a client to a server.
Establishes connection to server
Uses TCP protocol
Syntax:
Socket s = new Socket("localhost", 5000);
ServerSocket (Server)
Used to create server applications
3
Listens for client requests
Syntax:
ServerSocket ss = new ServerSocket(5000);
Socket s = [Link]();
URL and URLConnection
URL Represents web address
URLConnection Used to communicate with resource
Example:
import [Link].*;
class Demo {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
[Link]("Protocol: " + [Link]());
[Link]("Host: " + [Link]());
}
}
Networking Exceptions
UnknownHostException
IOException
SocketException
These exceptions occur during network failures.
Important Points
Socket is used by client
ServerSocket is used by server
InetAddress provides IP details
URL is used for web resources
7.3 Client-Server Communication (TCP/IP)
Introduction
Client-server communication is a model where a client sends a request and a server responds to it.
In Java, this is implemented using Socket and ServerSocket classes.
Server waits for client request
Client initiates communication
Communication occurs using streams
4
Steps in TCP Communication
1. Server creates ServerSocket
2. Server waits using accept()
3. Client creates Socket
4. Streams are created for communication
5. Data is sent and received
One-Way Communication
In one-way communication, data ows only from client to server.
Server Program:
import [Link].*;
import [Link].*;
class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(5000);
Socket s = [Link]();
DataInputStream dis =
new DataInputStream([Link]());
String msg = [Link]();
[Link]("Client: " + msg);
[Link]();
}
}
Client Program:
import [Link].*;
import [Link].*;
class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 5000);
DataOutputStream dos =
new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
}
}
Output (Server):
Client: Hello Server
Two-Way Communication
In two-way communication, both client and server send and receive messages.
Server Program:
5
import [Link].*;
import [Link].*;
class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(5000);
Socket s = [Link]();
DataInputStream dis =
new DataInputStream([Link]());
DataOutputStream dos =
new DataOutputStream([Link]());
String msg = [Link]();
[Link]("Client: " + msg);
[Link]("Hello Client");
[Link]();
}
}
Client Program:
import [Link].*;
import [Link].*;
class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 5000);
DataInputStream dis =
new DataInputStream([Link]());
DataOutputStream dos =
new DataOutputStream([Link]());
[Link]("Hello Server");
String reply = [Link]();
[Link]("Server: " + reply);
[Link]();
}
}
Output:
Server: Hello Client
Important Points
Server must start before client
Port number must match
TCP ensures reliable communication
Streams are used for data transfer
6
7.4 UDP Communication (DatagramSocket)
Introduction
UDP (User Datagram Protocol) is a connectionless communication protocol. Unlike TCP, it does
not guarantee delivery, ordering, or error checking.
Faster than TCP
No connection setup required
Used in real-time applications (video streaming, gaming)
DatagramSocket and DatagramPacket
DatagramSocket
Used to send and receive packets
DatagramPacket
Contains data, address, and port
Steps in UDP Communication
1. Create DatagramSocket
2. Create DatagramPacket
3. Send or receive data
UDP Sender Program
import [Link].*;
class Sender {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String msg = "Hello UDP";
InetAddress ip = [Link]("localhost");
DatagramPacket dp =
new DatagramPacket([Link](),
[Link](), ip, 5000);
[Link](dp);
[Link]();
}
}
UDP Receiver Program
7
import [Link].*;
class Receiver {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(5000);
byte[] buffer = new byte[1024];
DatagramPacket dp =
new DatagramPacket(buffer, [Link]);
[Link](dp);
String msg = new String([Link](), 0, [Link]());
[Link]("Received: " + msg);
[Link]();
}
}
Output:
Received: Hello UDP
TCP vs UDP
Feature TCP UDP
Connection Connection-oriented Connectionless
Reliability Reliable Unreliable
Speed Slower Faster
Data Order Maintained Not guaranteed
Important Points
UDP is faster but unreliable
No connection establishment required
Used in real-time applications
Uses DatagramSocket and DatagramPacket
7.5 Remote Method Invocation (RMI)
Introduction
Remote Method Invocation (RMI) allows a Java program to invoke methods on an object located on
another machine (remote system).
Enables distributed computing
Works on client-server model
Uses object-oriented communication
8
RMI Architecture
RMI consists of:
Client invokes remote method
Server provides remote object
Stub proxy for remote object
RMI Registry stores remote object reference
Working of RMI
1. Server creates remote object
2. Object is registered in RMI registry
3. Client looks up registry
4. Client invokes method via stub
Steps to Implement RMI
1. Create remote interface
2. Implement interface
3. Create server program
4. Create client program
5. Start RMI registry
6. Run server and client
Step 1: Remote Interface
import [Link].*;
public interface Add extends Remote {
int sum(int a, int b) throws RemoteException;
}
Step 2: Implementation
import [Link].*;
import [Link].*;
public class AddImpl extends UnicastRemoteObject
implements Add {
AddImpl() throws RemoteException {}
public int sum(int a, int b) {
return a + b;
}
}
9
Step 3: Server Program
import [Link].*;
public class Server {
public static void main(String[] args) {
try {
Add obj = new AddImpl();
[Link]("rmi://localhost/AddService", obj);
[Link]("Server ready");
} catch(Exception e) {
[Link]();
}
}
}
Step 4: Client Program
import [Link].*;
public class Client {
public static void main(String[] args) {
try {
Add obj = (Add) [Link](
"rmi://localhost/AddService");
int result = [Link](5, 3);
[Link]("Result: " + result);
} catch(Exception e) {
[Link]();
}
}
}
Execution Steps
1. Compile all files
2. Start RMI registry:
rmiregistry
3. Run server:
java Server
4. Run client:
java Client
Output:
Result: 8
Advantages of RMI
Supports distributed applications
Object-oriented communication
10
Simplies remote interaction
Important Points
Remote interface must extend Remote
Methods must throw RemoteException
RMI registry must be running
Stub handles communication
11