network programming
network programming
Answer:
A Java Echo Application allows a client to send a message to the server, and the server echoes it back. Below is
the Java program:
Server (EchoServer.java)
import java.io.*;
import java.net.*;
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected!");
String message;
while ((message = input.readLine()) != null) {
System.out.println("Received: " + message);
output.println("Echo: " + message);
}
socket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Client (EchoClient.java)
import java.io.*;
import java.net.*;
2. Write a client-side program to read information from the server using socket.
Answer:
import java.io.*;
import java.net.*;
String serverResponse;
while ((serverResponse = input.readLine()) != null) {
System.out.println("Server says: " + serverResponse);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
3. Write a program to perform basic text messaging between client and server.
Answer:
This Java program enables a simple chat between a client and a server.
Server (ChatServer.java)
import java.io.*;
import java.net.*;
Client (ChatClient.java)
import java.io.*;
import java.net.*;
serverMessage = input.readLine();
System.out.println("Server: " + serverMessage);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Answer:
The Client-Server Model is a network architecture where a server provides services, and clients request those
services.
Design Considerations:
Answer:
1. Connection-Oriented Networking:
o Requires an established connection before data transfer (e.g., TCP).
o Reliable and ensures data integrity.
o Used in applications like email, web browsing, and file transfers.
2. Connectionless Networking:
o No dedicated connection is required (e.g., UDP).
o Faster but less reliable.
o Used in applications like VoIP and online gaming.
Answer:
Scope:
7. What is the client-server software model? Explain the strengths and weaknesses of Java as a network
programming language.
Answer:
Weaknesses:
Performance Overhead: JVM adds some latency.
Memory Consumption: Requires more memory than C or C++.
8. Explain different Network Programming Tools and Platforms available in the market.
Answer:
Assignment 2 (Chapter:2)
Assingment- 3:
Q.1)WAP to add two numbers using RMI.
Q.6) What is RMI? Write a RMI Client and server program to find greater number among two numbers.
[advance java 2024]
Here is the complete solution with each question followed by its corresponding answer.
Answer:
To add two numbers using Java RMI, we need three main components:
1. Remote Interface (Addition.java)
2. Server Implementation (AdditionServer.java)
3. Client Implementation (AdditionClient.java)
import java.rmi.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
Answer:
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
Answer:
import java.rmi.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
Answer:
import java.rmi.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
Answer:
import java.rmi.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
Q.6) What is RMI? Write an RMI Client and Server program to find the greater number
among two numbers.
Answer:
RMI (Remote Method Invocation) is a mechanism in Java that allows an object to invoke methods on an
object running on another machine or JVM. It provides a way for Java programs to communicate over a
network by calling remote methods as if they were local methods.
import java.rmi.*;
import java.rmi.*;
Short Notes
i) RMI Server
RMI Server is the component that hosts and provides remote services. It registers remote objects with the RMI
Registry and listens for client requests. The main responsibilities of an RMI server include:
Example:
Naming.rebind("rmi://localhost/MyService", obj);
This completes all the questions with proper explanations and code. Let me know if you need further
clarifications! 🚀
2019
Client-Server Model
The Client-Server Model is a networking framework where a client requests services and a server provides
them. The client initiates communication, and the server responds.
Example
3. Write a Program to Show IP and MAC Address of the System and Check if the IP
Address is IPv4 or IPv6.
IP Address: 192.168.1.10
MAC Address: 00-1A-2B-3C-4D-5E
The IP Address is IPv4
4. Define URL Connection Class. Write a Program to Read Header Using Header-
Specific Methods.
URLConnection is a Java class used to establish a connection with a URL. It allows sending requests, receiving
responses, and reading headers from a web page or API.
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. Write the Functions of Socket. Explain the Configuration Options of TCP Client
Socket.
Functions of a Socket
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Definition of Buffer
A buffer is a temporary storage area used to store data before processing. In networking, buffers handle
incoming and outgoing data streams.
a) HTTP Methods
b) Datagram Packet
A DatagramPacket is used in UDP communication. It represents a data packet sent or received over a network
without establishing a connection.
c) Multicast Socket
A MulticastSocket allows a sender to send packets to multiple receivers simultaneously. It is useful for video
streaming and live broadcasts.
9(a) Differentiate Between URL and URI Class with Their Applications
Feature URL (Uniform Resource Locator) URI (Uniform Resource Identifier)
Definition A specific address to locate a resource on the web. A general term that includes both URLs and URNs.
mailto:[email protected],
Example https://www.example.com/page.html
urn:isbn:0451450523
Components Protocol (HTTP/HTTPS), domain, and resource path. Can be a URL or URN (Uniform Resource Name).
Applications
URL: Used for accessing web pages, APIs, and downloading resources.
URI: Used for general resource identification, including email addresses and ISBN numbers.
10. Write a TCP Multithreaded Server and Client Socket Program to Check if a
Number Sent by the Client is Prime or Composite.
out.println(number);
System.out.println("Server Response: " + in.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ How It Works:
11. Write a Program to Create UDP Server and Client Which Converts Date from
BS to AD Format.
Assumption:
if (adMonth <= 0) {
adMonth += 12;
adYear--;
}
if (adDay <= 0) {
adDay += 30;
adMonth--;
}
2018
2. Define Client Server software model. Explain the features of Java as a Network programming
language.
Answer:
The client-server software model is a distributed application architecture where tasks are divided between
servers, which provide resources or services, and clients, which request those services.
Server: A server is a program that listens for incoming requests from clients and provides the requested
services. It typically runs on a powerful machine with ample resources.
Client: A client is a program that initiates requests to the server for specific services. It typically runs on
a user's machine or device.
Platform Independence: Java's "write once, run anywhere" capability allows network applications to
run on various operating systems without modification.
Rich Networking API: Java provides a comprehensive set of classes and interfaces in the java.net
package, making it easy to develop network applications.
Object-Oriented: Java's object-oriented nature promotes code reusability, modularity, and
maintainability, which are essential for complex network applications.
Multithreading: Java's built-in multithreading support allows servers to handle multiple client requests
concurrently, improving performance and scalability.
Security Features: Java includes robust security features, such as code verification and security
managers, which are crucial for protecting network applications from threats.
Exception Handling: Java's exception handling mechanism allows developers to write robust and fault-
tolerant network applications.
3. What is the use of NetworkInterface Class? Explain the basic features of NetworkInterface class.
Answer:
The NetworkInterface class in Java represents a network interface, which can be a physical or virtual network
adapter. It provides methods to access information about network interfaces, such as their names, addresses, and
hardware addresses.
Basic Features of NetworkInterface Class:
Retrieving Network Interfaces: The NetworkInterface class provides static methods like
getNetworkInterfaces() and getByName() to retrieve network interfaces.
Accessing Interface Information: It offers methods to get the name (getName()), display name
(getDisplayName()), hardware address (getHardwareAddress()), and MTU (getMTU()) of a network
interface.
Retrieving IP Addresses: The getInetAddresses() method returns an enumeration of all IP addresses
assigned to the network interface.
Checking Interface Status: Methods like isUp(), isLoopback(), isVirtual(), and
isPointToPoint() allow you to check the status and type of a network interface.
Subinterfaces: The getSubInterfaces() method returns an enumeration of subinterfaces associated
with the network interface.
Answer:
HTTP Methods:
HTTP (Hypertext Transfer Protocol) defines a set of methods that indicate the desired action to be performed on
a resource identified by a given URI.
GET: Retrieves a resource. It is used for read-only operations and should not modify the server state.
o Example: GET /index.html HTTP/1.1
POST: Submits data to be processed to a specified resource. It is often used for creating or updating
resources.
o Example: Submitting a form with user data.
PUT: Replaces all current representations of the target resource with the request payload.
o Example: Uploading a file to a specific location on the server.
DELETE: Deletes the specified resource.
o Example: Deleting a blog post or a user account.
HEAD: Same as GET, but only retrieves the headers, not the message body.
o Example: Checking the existence of a resource or its last modification time.
OPTIONS: Describes the communication options for the target resource.
o Example: Determining which HTTP methods are supported by the server.
TRACE: Performs a message loop-back test along the path to the target resource.
o Example: Debugging proxy or firewall issues.
CONNECT: Establishes a tunnel to the server identified by the target resource.
o Example: Used for establishing secure connections through proxies.
5. Write a program to display the socket information [address, port, local address, local port].
Answer:
Java
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Answer:
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
7. Define Non-blocking I/O. Differentiate between blocking and non-blocking socket communication in
Java.
Answer:
Non-blocking I/O:
Non-blocking I/O is a mode of operation where I/O operations (such as reading from or writing to a socket)
return immediately, even if the operation cannot be completed. The calling thread does not wait for the
operation to finish.
Blocking Sockets:
o When a thread performs a blocking I/O operation (e.g., read() or accept()), it waits until the
operation completes.
o If no data is available or no connection is made, the thread is blocked (suspended) until the I/O
operation can proceed.
o Simpler to use but can lead to performance issues if multiple clients are handled by a single
thread.
Non-blocking Sockets:
o I/O operations return immediately, even if they cannot be completed.
o The thread can perform other tasks while waiting for I/O operations to complete.
o Requires more complex code to handle the asynchronous nature of I/O.
o Improves performance and scalability by allowing a single thread to manage multiple
connections.
o Java's NIO (New I/O) package provides support for non-blocking I/O using channels and
selectors.
a) Secure Communication
Answer:
Secure communication involves protecting data transmitted over a network from unauthorized access,
modification, or disclosure. It relies on cryptographic techniques to ensure confidentiality, integrity, and
authentication.
Confidentiality: Ensures that only authorized parties can access the data. Achieved through encryption.
Integrity: Ensures that data is not altered during transmission. Achieved through hashing and digital
signatures.
Authentication: Verifies the identity of the communicating parties. Achieved through digital
certificates and passwords.
Protocols: Common secure communication protocols include SSL/TLS, HTTPS, SSH, and VPNs.
b) Multicast Sockets
Answer:
Multicast sockets allow data to be sent to multiple recipients simultaneously. Instead of sending data to a single
destination, multicast sends data to a group of recipients identified by a multicast IP address.
Group Communication: Multicast is used for applications that require group communication, such as
video conferencing, online gaming, and stock ticker updates.
Efficiency: Multicast is more efficient than unicast (sending data to each recipient individually) when
sending data to multiple recipients.
IP Addresses: Multicast uses a special range of IP addresses
9. What is the Procedure of Socket Communication?
A socket is an endpoint for sending or receiving data across a network. The basic procedure for socket communication is
as follows:
A socket has several configuration options that determine its behavior. These options can be modified using the
setOption() method.
Option Description
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This program demonstrates a simple two-way communication where the client sends a message and the server
responds.
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ How It Works:
while (true) {
// Receiving data from client
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
serverSocket.receive(receivePacket);
String receivedData = new String(receivePacket.getData(), 0,
receivePacket.getLength());
✅ How It Works:
2019
9. What is the procedure for constructing and connecting Server sockets? Explain the Server Socket
options with example.
Answer:
1. Create a ServerSocket:
o Instantiate a ServerSocket object, specifying the port number on which the server will listen for
incoming connections.
o ServerSocket serverSocket = new ServerSocket(port);
2. Listen for Connections:
o Call the accept() method on the ServerSocket object. This method blocks until a client
attempts to connect.
o Socket clientSocket = serverSocket.accept();
3. Handle Client Connection:
o The accept() method returns a Socket object representing the connection with the client.
o Use the Socket object to communicate with the client (e.g., read input, write output).
4. Close the Sockets:
o After the communication is complete, close the Socket and ServerSocket objects to release
resources.
o clientSocket.close();
o serverSocket.close();
setSoTimeout(int timeout): Sets the timeout for the accept() method. If no client connection is
established within the specified timeout, a SocketTimeoutException is thrown.
o Example:
Java
Java
setReuseAddress(boolean on): Enables or disables the SO_REUSEADDR socket option. This option
allows the server to bind to a port even if it was recently used by another process.
o Example:
Java
10. Write a program to perform a basic two-way communication between client and server.
Answer:
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
out.println("Server received: " + inputLine);
}
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Code (Client.java):
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
while (true) {
System.out.print("Enter message (or 'exit'): ");
userInput = scanner.nextLine();
out.println(userInput);
if (userInput.equalsIgnoreCase("exit")) {
break;
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
11. What are features of DatagramPacket and Datagramsocket Class? Write a program to create a
simple UDP client.
Answer:
DatagramPacket:
o Represents a datagram packet, which is a unit of data that can be sent or received over a network
using UDP.
o Contains the data to be sent or received, the destination or source address, and the destination or
source port.
o Used for connectionless communication, where packets are sent independently and may arrive
out of order or be lost.
DatagramSocket:
o Represents a socket for sending and receiving datagram packets.
o Used for connectionless communication over UDP.
o Can be used to send and receive datagram packets to and from any destination.
Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
System.out.println("Message sent.");
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This client sends a message to a server running on localhost at port 9876. To test this, you would need to create
a UDP server that listens on that port.
Alright, let's tackle the Network Programming exam paper from the 2018 batch, question by question.
Group B
12. What is Client-Server software model? Explain the strengths and weaknesses of Java programming
as a network programming language.
Answer:
The client-server software model is a distributed application architecture where tasks are divided between
servers and clients.
Platform Independence: Java's "write once, run anywhere" capability allows network applications to
run on various operating systems without modification.
Rich Networking API: Java provides a comprehensive set of classes and interfaces in the java.net
package, making it easy to develop network applications.
Object-Oriented: Java's object-oriented nature promotes code reusability, modularity, and
maintainability.
Multithreading: Java's built-in multithreading support allows servers to handle multiple client requests
concurrently.
Security Features: Java includes robust security features, such as code verification and security
managers.
Exception Handling: Java's exception handling mechanism allows developers to write robust and fault-
tolerant network applications.
Performance Overhead: Java's virtual machine can introduce some performance overhead compared to
languages like C or C++.
Verbose Syntax: Java's syntax can be more verbose than some other languages, which can increase
development time.
Memory Consumption: Java applications can sometimes consume more memory than applications
written in other languages.
13. What is the use of InetAddress class? Write a program to retrieve IP and MAC address?
Answer:
The InetAddress class in Java represents an Internet Protocol (IP) address. It is used to get the IP address of a
host (machine) and to perform operations on IP addresses.
Java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
14. Define URL class. Write a program to show the parts of the URL (Splitting URL).
Answer:
URL Class:
The URL class in Java represents a Uniform Resource Locator (URL), which is a reference to a resource on the
World Wide Web.
Java
import java.net.MalformedURLException;
import java.net.URL;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
15. Define Socket. Differentiate between TCP and UDP Sockets with their applications.
Answer:
Socket:
A socket is an endpoint for communication between two machines over a network. It provides an interface for
sending and receiving data.
16. Define cookies. Write a program to retrieve cookie information stored in the system.
Answer:
Cookies:
Cookies are small pieces of data that a server sends to a client's web browser. The browser may store the
cookies and send them back to the server with later requests. Cookies are used for various purposes, such as
session management, personalization, and tracking.
Retrieving cookie information directly from the system is generally not possible with Java's standard libraries.
Cookies are typically managed by web browsers. To retrieve cookies, you would need to use a web browser
automation tool or a library that interacts with the browser's cookie storage.
17. Define IP Multicast. Write a program to join a computer system in a multicast group.
Answer:
IP Multicast:
IP multicast is a network communication technique for delivering data to a group of recipients simultaneously.
Instead of sending data to each recipient individually, the sender sends data to a multicast group address.
Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
socket.leaveGroup(group);
} catch (IOException e) {
e.printStackTrace();
}
}
}
a) HTTP
Answer:
HTTP (Hypertext Transfer Protocol) is an application-layer protocol for distributed, collaborative, hypermedia
information systems. It is the foundation of data communication for the World Wide Web. HTTP is a request-
response protocol in the client-server model.
Methods: HTTP defines methods like GET, POST, PUT, DELETE, etc., to indicate the desired action.
Headers: HTTP messages include headers that provide metadata about the request or response.
Status Codes: HTTP responses include status codes that indicate the outcome of the request.
b) RMI
Answer:
RMI (Remote Method Invocation) is a Java API that allows an object running in one Java virtual machine
(JVM) to invoke methods on an object running in another JVM. RMI enables distributed computing in Java.
Remote Interfaces: RMI uses remote interfaces to define the methods that can be invoked remotely.
Stubs and Skeletons: RMI generates stubs and skeletons to handle communication between the client
and server JVMs.
Registry: RMI uses a registry to locate remote objects.
c) Secure Socket
Answer:
A secure socket is a socket that provides secure communication over a network using encryption and
authentication protocols, such as SSL/TLS. This ensures that data is protected from eavesdropping and
tampering.
19. Write multithreaded TCP client and server socket programs for daytime service.
Answer:
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
@Override
public void run() {
try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true))
{
out.println(new Date().toString());
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
} catch (IOException e) {
e.printStackTrace();
}
}
}
20. Write UDP client and server socket programs in which the server identifies the number sent by a
client is either even or odd and replies to client accordingly.
Answer:
Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
} catch (IOException e) {
e.printStackTrace();
}
}
}
21. How blocking I/O is differing from Non-Blocking I/O? Explain the basic mechanism of handling
Buffers and Channels in Java with example.
Answer:
Blocking I/O:
o When a thread performs a blocking I/O operation (e.g., read() or accept()), it waits until the
operation completes.
o If no data is available or no connection is made, the thread is blocked (suspended) until the I/O
operation can proceed.
o Simpler to use but can lead to performance issues if multiple clients are handled by a single
thread.
Non-Blocking I/O:
o I/O operations return immediately, even if they cannot be completed.
o The thread can perform other tasks while waiting for I/O operations to complete.
o Requires more complex code to handle the asynchronous nature of I/O.
o Improves performance and scalability by allowing a single thread to manage multiple
connections.
o Java's NIO (New I/O) package provides support for non-blocking I/O using channels and
selectors.
Java NIO (New I/O) provides channels and buffers for non-blocking I/O.
Channels:
o Represent connections to I/O devices (e.g., files, sockets).
o Can be used for reading and writing data.
o Support non-blocking operations.
Buffers:
o Hold data temporarily during I/O operations.
o Provide methods for reading and writing data, as well as for managing their position, limit, and
capacity.
Example:
Java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
} catch (IOException e) {
e.printStackTrace();
}
}
}
RR Campus
1. Write a java program using TCP that enables chatting between client and server.
Answer:
Java
import java.io.*;
import java.net.*;
while (true) {
if ((clientMessage = in.readLine()) != null) {
System.out.println("Client: " + clientMessage);
System.out.print("Server: ");
serverMessage = consoleIn.readLine();
out.println(serverMessage);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java
import java.io.*;
import java.net.*;
while (true) {
System.out.print("Client: ");
clientMessage = consoleIn.readLine();
out.println(clientMessage);
Answer:
Answer:
RMI is a Java API that allows an object running in one Java virtual machine (JVM) to invoke methods on an
object running in another JVM. It enables distributed computing in Java.
RMI Architecture:
4. What is InetAddress class? Explain the IPv4 Socket Address Structure and IPv6 Socket Address
Structure.
Answer:
InetAddress Class:
The InetAddress class represents an Internet Protocol (IP) address. It is used to get the IP address of a host and
to perform operations on IP addresses.
5. What are the core components consist of Java NIO? Explain any two.
Answer:
Buffers: Buffers are used to hold data during I/O operations. They provide methods for reading and
writing data, as well as for managing their position, limit, and capacity.
Channels: Channels represent connections to I/O devices. They can be used for reading and writing
data, and they support non-blocking operations.
6. What is a Port? Create a simple port scanner program to check the open ports for the specified host
name.
Answer:
Port:
A port is a 16-bit number that identifies a specific process or service running on a host.
Java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
Answer:
Cookie:
A cookie is a small piece of data that a server sends to a client's web browser. The browser may store the cookie
and send it back to the server with later requests.
CookieHandler: An abstract class that provides a framework for implementing HTTP cookie
management.
CookieManager: A concrete implementation of CookieHandler that manages the storage and retrieval
of cookies.
CookiePolicy: Defines the rules for accepting or rejecting cookies.
CookieStore: An interface that represents a storage for cookies.
HttpCookie: A class that represents an HTTP cookie.
Group - C
Answer:
HTTP Methods:
Examples:
Java
import java.io.*;
import java.net.*;
public class ReverseTextServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Reverse Text Server started on port 8080...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
String clientMessage;
while ((clientMessage = in.readLine()) != null) {
if (clientMessage.equalsIgnoreCase("EXIT")) {
break;
}
String reversedMessage = new
StringBuilder(clientMessage).reverse().toString();
out.println(reversedMessage);
}
System.out.println("Client disconnected.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java
import java.io.*;
import java.net.*;
import java.util.Scanner;
String userInput;
while (true) {
System.out.print("Enter text (or EXIT): ");
userInput = scanner.nextLine();
out.println(userInput);
if (userInput.equalsIgnoreCase("EXIT")) {
break;
}
Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
} catch (IOException e) {
e.printStackTrace();
}
}
}
2024
The URLConnection class in Java is used to retrieve and read HTTP headers. The process involves the
following steps:
1. Create a URL Object: Define the URL you want to connect to.
2. Open a Connection: Use openConnection() to create a URLConnection object.
3. Connect to the Server: Call connect() to establish a connection.
4. Retrieve Header Fields: Use getHeaderField() and getHeaderFieldKey() to read the HTTP headers.
✅ Explanation:
a) x-www-form-urlencoded Encoder
b) URI Decoder
// Encoding
String encoded = URLEncoder.encode(original, "UTF-8");
System.out.println("Encoded: " + encoded);
// Decoding
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Decoded: " + decoded);
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Output:
Encoded: Hello+World%21+%40+Java
Decoded: Hello World! @ Java
// Filtering cookies
if (headers.containsKey("Set-Cookie")) {
for (String cookie : headers.get("Set-Cookie")) {
if (cookie.contains(".gov")) {
System.out.println("Blocked Cookie: " + cookie);
} else {
System.out.println("Allowed Cookie: " + cookie);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Explanation:
Definition:
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Explanation:
Java NIO (Non-blocking I/O) provides high-performance data processing. The main abstractions are:
✅ Explanation:
A Multicast Group allows sending data to multiple clients using one transmission.
Uses Multicast IP (224.0.0.0 – 239.255.255.255).
Multicast Server
import java.net.*;
Multicast Client
import java.net.*;
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass but
allows subclasses to alter the type of objects that will be created.
It helps achieve loose coupling, abstraction, and reusability.
✅ Output:
Laptop is computing...
Desktop is computing...
🚀 Benefits:
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
System.out.println("Webpage downloaded successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Explanation:
Opens a URL connection and reads the HTML content line by line.
Saves the webpage content to a file (downloaded_page.html).
10. Key Differences Between Socket and ServerSocket & Console Chat Application
using TCP
Purpose Used by client to establish a connection. Used by server to listen for incoming connections.
Socket socket = new Socket(host, ServerSocket server = new
Creation port); ServerSocket(port);
Usage Used for sending/receiving data. Accepts client connections via accept().
🔹 Server Code
import java.io.*;
import java.net.*;
while (true) {
message = reader.readLine();
if (message.equalsIgnoreCase("exit")) {
System.out.println("Client disconnected.");
break;
}
System.out.println("Client: " + message);
System.out.print("You: ");
message = console.readLine();
writer.println(message);
}
socket.close();
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
🔹 Client Code
import java.io.*;
import java.net.*;
while (true) {
System.out.print("You: ");
message = console.readLine();
writer.println(message);
if (message.equalsIgnoreCase("exit")) {
System.out.println("Disconnected from server.");
break;
}
message = reader.readLine();
System.out.println("Server: " + message);
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ How It Works:
11. RMI Program to Calculate Area of a Triangle & List Network Interfaces
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
import java.rmi.registry.*;
while (interfaces.hasMoreElements()) {
NetworkInterface netInt = interfaces.nextElement();
System.out.println("Interface: " + netInt.getName());
Enumeration<InetAddress> addresses = netInt.getInetAddresses();
while (addresses.hasMoreElements()) {
System.out.println(" Address: " + addresses.nextElement());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Output Example:
Interface: eth0
Address: 192.168.1.2
Address: fe80::1
Interface: lo
Address: 127.0.0.1
2023
The client-server model is a distributed application structure that separates tasks between providers (servers)
and requesters (clients).
Example: Web applications where browsers (clients) request data from web servers.
Strengths Weaknesses
Platform-independent (Write once, run anywhere). Slightly slower than native languages like C/C++.
Built-in networking libraries (e.g., Socket, URL, InetAddress). Higher memory consumption.
Robust security features (Java Secure Socket Extension - JSSE). Requires JVM installation on client machines.
Supports both multi-threading and asynchronous I/O (NIO). Higher latency in real-time applications.
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Output Example:
IP Address: 192.168.1.5
MAC Address: 3C-4A-92-AB-CD-01
The URL (Uniform Resource Locator) class in Java represents a web address.
It provides methods to extract different parts of a URL (protocol, domain, port, etc.).
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Output:
Protocol: https
Host: www.example.com
Port: 8080
Path: /path/page.html
Query: query=java
Ref (Fragment): section1
a) Definition of Socket
Reliability Reliable (ensures delivery & order). Unreliable (no guarantee of delivery).
a) Definition of Cookies
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Output:
a) Definition of IP Multicast
✅ Output:
Java RMI (Remote Method Invocation) allows invoking methods on remote objects.
Uses rmiregistry for server-client communication.
Supports distributed computing.
Example: Online banking transactions.
This server listens for client requests and sends the current date and time.
java
CopyEdit
import java.io.*;
import java.net.*;
import java.util.Date;
while (true) {
Socket clientSocket = serverSocket.accept();
new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The client connects to the server and receives the current date and time.
java
CopyEdit
import java.io.*;
import java.net.*;
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Run the server first, then run multiple clients to see the response.
This server listens for a number from the client, checks if it's even or odd, and responds accordingly.
java
CopyEdit
import java.net.*;
while (true) {
serverSocket.receive(receivePacket);
String receivedData = new String(receivePacket.getData(), 0,
receivePacket.getLength());
int number = Integer.parseInt(receivedData.trim());
String response = (number % 2 == 0) ? "Even" : "Odd";
b) UDP Client
The client sends a number to the server and gets a response about whether it's even or odd.
java
CopyEdit
import java.net.*;
import java.util.Scanner;
✅ Run the server first, then run the client and enter numbers to see the response.
11. Blocking vs. Non-Blocking I/O & Buffers and Channels in Java
Behavior Waits until the operation completes. Doesn't wait; continues execution.
Thread Usage Each connection needs a separate thread. Uses a single thread for multiple connections.
✅ Example:
This program writes data into a file using NIO (Non-blocking I/O).
java
CopyEdit
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
} catch (IOException e) {
e.printStackTrace();
}
}
}