Experiment 1: Write a Java program that accepts a domain name (e.g., "[Link].
com") as
input and does the following:
a) Create an InetAddress object for the domain using different factory methods (getByName,
getAllByName).
b) Print the hostname, canonical hostname, and IP address of each resolved InetAddress.
c) Detect whether each address is an IPv4 (Inet4Address) or IPv6 (Inet6Address) and print
the type.
d) Test whether each address is reachable within 5 seconds using isReachable().
e) Demonstrate the use of object methods (equals(), hashCode(), toString()) on at least two
of the resolved InetAddress objects.
SOURCE CODE:
import [Link].*;
import [Link].*;
public class Experiment1 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter domain: ");
String domain = [Link]();
InetAddress one = [Link](domain);
InetAddress[] all = [Link](domain);
for (InetAddress a : all) {
[Link]("Host: " + [Link]());
[Link]("Canonical: " + [Link]());
[Link]("IP: " + [Link]());
[Link]("Type: " + (a instanceof Inet4Address ? "IPv4"
: a instanceof Inet6Address ? "IPv6" : "Unknown"));
[Link]("Reachable: " + [Link](5000));
[Link]();
}
if ([Link] > 1) {
[Link]("Equals: " + all[0].equals(all[1]));
Mahendra Mahara – BCA 6th
[Link]("Hash1: " + all[0].hashCode());
[Link]("Hash2: " + all[1].hashCode());
[Link]("ToString1: " + all[0]);
[Link]("ToString2: " + all[1]);
}
}
}
OUTPUT:
Experiment 2: Write a Java program to obtain and manipulate the IP addresses of a system. Also,
it should get and interact with another domain to demonstrate, and the program should check
whether an address is reachable and identify if it is IPv4 or IPv6.
SOURCE CODE:
import [Link].*;
public class Experiment2 {
public static void main(String[] args) throws Exception {
Mahendra Mahara – BCA 6th
InetAddress local = [Link]();
[Link]("Local Host: " + [Link]());
[Link]("Local IP: " + [Link]());
[Link]("Type: " + (local instanceof Inet4Address ? "IPv4"
: local instanceof Inet6Address ? "IPv6" : "Unknown"));
[Link]("Reachable: " + [Link](5000));
[Link]();
InetAddress remote =
[Link]("[Link]");
[Link]("Remote Host: " + [Link]());
[Link]("Remote IP: " + [Link]());
[Link]("Type: " + (remote instanceof Inet4Address ?
"IPv4" : remote instanceof Inet6Address ? "IPv6" : "Unknown"));
[Link]("Reachable: " + [Link](5000));
}
}
OUTPUT:
Experiment 3: Write a Java program that demonstrates working with URLs and URIs by creating
a URL, printing its parts, fetching data, comparing two URLs, constructing a URI, printing its
components, resolving a relative URI, and converting between URI and URL.
SOURCE CODE:
import [Link].*;
Mahendra Mahara – BCA 6th
public class Experiment3 {
public static void main(String[] args) throws Exception {
URL url1 = new URL("[Link]
[Link]("Protocol: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Path: " + [Link]());
[Link]("Query: " + [Link]());
[Link]("Ref: " + [Link]());
[Link]("Content: " + [Link]());
[Link]();
URL url2 = new URL("[Link]
[Link]("URL1 equals URL2: " + [Link](url2));
[Link]("CompareTo: " +
[Link]().compareTo([Link]()));
[Link]();
URI uri1 = new URI("[Link]
[Link]("Scheme: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Path: " + [Link]());
[Link]("Query: " + [Link]());
[Link]("Fragment: " + [Link]());
[Link]("Back to URL: " + [Link]());
[Link]();
URI base = new URI("[Link]
URI rel = new URI("sub/[Link]");
URI resolved = [Link](rel);
[Link]("Resolved URI: " + resolved);
[Link]();
Mahendra Mahara – BCA 6th
URI uri2 = new URI("[Link]
[Link]("URI1 equals URI2: " + [Link](uri2));
[Link]("URI1 toString: " + [Link]());
[Link]("URI2 toString: " + [Link]());
}
}
OUTPUT:
Experiment 4: Write a Java program that sends data to a server using x-www-form-urlencoded
(URL encoder/decoder), communicates through a proxy (using System properties, Proxy, or
ProxySelector), performs a GET request to a server-side program, and demonstrates accessing a
password-protected site using the Authenticator, PasswordAuthentication, and JPasswordField
classes.
SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment4 {
Mahendra Mahara – BCA 6th
public static void main(String[] args) throws Exception {
String data = "name=" + [Link]("Mahendra", "UTF-8") +
"&course=" + [Link]("BCA", "UTF-8");
[Link]("Encoded: " + data);
[Link]("Decoded: " + [Link](data, "UTF-8"));
[Link]("[Link]", "[Link]");
[Link]("[Link]", "8080");
Proxy proxy = new Proxy([Link], new
InetSocketAddress("[Link]", 8080));
URL url = new URL("[Link] + data);
HttpURLConnection con = (HttpURLConnection)
[Link](proxy);
[Link]("GET");
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()));
String line; while ((line = [Link]()) != null)
[Link](line);
[Link]();
[Link](new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
JPasswordField pf = new JPasswordField();
[Link](null, pf, "Enter Password",
JOptionPane.OK_CANCEL_OPTION);
return new PasswordAuthentication("user", [Link]());
}
});
URL secure = new URL("[Link]
auth/user/mahendra@1234");
HttpURLConnection secCon = (HttpURLConnection)
[Link]();
[Link]("Protected Site Response: " +
[Link]());
}
}
Mahendra Mahara – BCA 6th
[note: I have created a proxy server using [Link]]
OUTPUT:
Experiment 5: Write a Java program that sends an HTTP request to a server using different HTTP
methods (GET, POST), includes a request body when needed, demonstrates Keep-Alive
connections, and manages cookies using CookieManager and CookieStore.
SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment5 {
public static void main(String[] args) throws Exception {
CookieManager manager = new CookieManager();
[Link](manager);
URL getUrl = new URL("[Link]
Mahendra Mahara – BCA 6th
HttpURLConnection getCon = (HttpURLConnection)
[Link]();
[Link]("GET");
[Link]("Connection", "keep-alive");
[Link]("GET Response: " + [Link]());
readResponse(getCon);
URL postUrl = new URL("[Link]
HttpURLConnection postCon = (HttpURLConnection)
[Link]();
[Link]("POST");
[Link](true);
[Link]("Content-Type", "application/x-www-form-
urlencoded");
[Link]("Connection", "keep-alive");
String data = "name=Mahendra&course=BCA";
try (OutputStream os = [Link]()) {
[Link]([Link]());
}
[Link]("POST Response: " + [Link]());
readResponse(postCon);
URL cookieUrl = new
URL("[Link]
HttpURLConnection cookieCon = (HttpURLConnection)
[Link]();
[Link]("Cookie Set Response: " +
[Link]());
readResponse(cookieCon);
CookieStore store = [Link]();
List<HttpCookie> cookies = [Link]();
[Link]("Stored Cookies:");
for (HttpCookie c : cookies) [Link](c);
}
static void readResponse(HttpURLConnection con) throws Exception {
Mahendra Mahara – BCA 6th
try (BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()))) {
String line;
while ((line = [Link]()) != null) [Link](line);
}
}
}
OUTPUT:
Mahendra Mahara – BCA 6th
Experiment 6: Write a Java program that opens a URLConnection to a given URL, reads and
prints the server’s data, retrieves specific and arbitrary header fields, and demonstrates the use of
web caching in Java.
SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment6 {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
URLConnection con = [Link]();
[Link](true);
[Link]("Date: " + new Date([Link]()));
[Link]("Content-Type: " + [Link]("Content-
Type"));
[Link]("Content-Length: " + [Link]());
[Link]("\nAll Headers:");
Map<String, List<String>> headers = [Link]();
for (String k : [Link]()) [Link](k + ": " +
[Link](k));
[Link]("\nData:");
try (BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()))) {
String line;
while ((line = [Link]()) != null) [Link](line);
}
URLConnection cached = [Link]();
[Link](true);
[Link]("\nUsing cache? " + [Link]());
}
Mahendra Mahara – BCA 6th
}
OUTPUT:
Experiment 7: Write a Java program that configures a URLConnection and HttpURLConnection
with properties like doInput, doOutput, useCaches, and timeouts, sets custom HTTP headers,
handles server responses, uses a proxy, guesses the MIME type of received content, demonstrates
streaming mode, and considers basic URLConnection security.
SOURCE CODE:
import [Link].*;
import [Link].*;
public class Experiment7 {
public static void main(String[] args) throws Exception {
Proxy proxy = new Proxy([Link], new
InetSocketAddress("[Link]", 8080));
Mahendra Mahara – BCA 6th
URL url = new URL("[Link]
HttpURLConnection con = (HttpURLConnection)
[Link](proxy);
[Link](true);
[Link](true);
[Link](false);
[Link](5000);
[Link](5000);
[Link]("POST");
[Link]("User-Agent", "JavaClient/1.0");
[Link]("Content-Type", "application/x-www-form-
urlencoded");
[Link]("Custom-Header", "CoolExperiment");
String data = "name=Mahendra&course=BCA";
[Link]([Link]());
try (OutputStream os = [Link]()) {
[Link]([Link]());
}
[Link]("Response Code: " + [Link]());
[Link]("Response Message: " + [Link]());
String contentType = [Link]("Content-Type");
if (contentType == null || [Link]()) {
contentType =
[Link]([Link]());
}
[Link]("MIME Type: " + contentType);
try (BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()))) {
String line;
while ((line = [Link]()) != null) [Link](line);
Mahendra Mahara – BCA 6th
}
[Link]("Security: Avoid exposing sensitive data in
headers or query params");
}
}
OUTPUT:
Experiment 8: Write a Java program that creates ServerSockets to serve binary data and handle
multiple clients using multithreading. The program should demonstrate writing to and closing
sockets, logging server activity, constructing server sockets without binding, retrieving server
socket information, configuring socket options (SO_TIMEOUT, SO_REUSEADDR,
SO_RCVBUF, Class of Service), and implementing basic HTTP server functionality such as
serving a single file, redirecting requests, and handling full-fledged HTTP responses.
SOURCE CODE:
import [Link].*;
Mahendra Mahara – BCA 6th
import [Link].*;
import [Link].*;
public class Experiment8 {
public static void main(String[] a) throws Exception {
ServerSocket ss = new ServerSocket();
[Link](true);
[Link](new InetSocketAddress("localhost",6000));
[Link](0);
[Link]("Server running on localhost:6000");
while(true) new Thread(() -> {
try(Socket s=[Link]()){
[Link](0x10);
[Link](8192);
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]()));
OutputStream out=[Link]();
String line=[Link]();
if(line==null)return;
StringTokenizer st=new StringTokenizer(line);
[Link]();
String path=[Link]();
if([Link]("/")){
File f=new File("[Link]");
if([Link]()){
byte[]data=new byte[(int)[Link]()];
new FileInputStream(f).read(data);
[Link](("HTTP/1.1 200 OK\r\nContent-
Length:"+[Link]+"\r\n\r\n").getBytes());
[Link](data);
}else [Link]("HTTP/1.1 404 Not Found\r\n\r\nNot
Found".getBytes());
}else if([Link]("/go")){
[Link]("HTTP/1.1 302
Found\r\nLocation:/\r\n\r\n".getBytes());
}else{
Mahendra Mahara – BCA 6th
String msg="<html><body><h1>Hello from Nahendra Mahara's
Server</h1></body></html>";
[Link](("HTTP/1.1 200 OK\r\nContent-
Length:"+[Link]()+"\r\n\r\n").getBytes());
[Link]([Link]());
}
[Link]();
}catch(Exception e){[Link](e);}
}).start();
}
}
OUTPUT:
Experiment 9: Write a Java program for ClientSocket that creates and connects sockets to a
server, reads and writes data, investigates protocols using tools like Telnet, and allows choosing a
local interface or using a proxy. The program should display socket information (toString(),
connected/closed status), configure socket options (TCP_NODELAY, SO_LINGER,
SO_TIMEOUT, SO_RCVBUF, SO_SNDBUF, SO_KEEPALIVE, OOBINLINE,
SO_REUSEADDR, IP_TOS).
SOURCE CODE:
import [Link].*;
import [Link].*;
public class Experiment9 {
public static void main(String[] a) throws Exception {
Socket s = new Socket();
[Link](true);
Mahendra Mahara – BCA 6th
[Link](true);
[Link](true);
[Link](false);
[Link](5000);
[Link](true, 2);
[Link](8192);
[Link](8192);
[Link](0x10);
[Link](new InetSocketAddress("localhost",6000));
[Link]("Socket: " + s);
[Link]("Connected: " + [Link]());
[Link]("Closed: " + [Link]());
OutputStream out = [Link]();
InputStream in = [Link]();
// Requesting the / path instead of /g
String req = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
[Link]([Link]());
[Link]();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
[Link]("=== HTTP HEADERS ===");
while((line = [Link]()) != null) {
[Link](line);
if([Link]()) break;
}
[Link]("=== HTML CONTENT ===");
while((line = [Link]()) != null) {
[Link](line);
}
Mahendra Mahara – BCA 6th
[Link]();
[Link]("Closed: " + [Link]());
}
}
OUTPUT:
Experiment 10: Write a Java program that implements a client-server communication system
where the client sends a message to the server, the server processes the message, and sends a
response back. The program should handle multiple clients, ensure proper socket connection and
disconnection, and display both client requests and server responses in a clear format.
SOURCE CODE [SERVER] :
import [Link].*;
import [Link].*;
public class Experiment10Server {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(7000);
Mahendra Mahara – BCA 6th
[Link]("Server running on port 7000");
while (true) {
Socket socket = [Link]();
new Thread(() -> {
try (
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new
PrintWriter([Link](), true)
) {
String msg;
while ((msg = [Link]()) != null) {
[Link]("Client: " + msg);
String response = "Server received: " +
[Link]();
[Link](response);
[Link]("Response: " + response);
}
} catch (Exception e) {
[Link]("Client disconnected");
}
}).start();
}
}
}
[SERVER OUTPUT]:
SOURCE CODE [CLIENT]:
Mahendra Mahara – BCA 6th
import [Link].*;
import [Link].*;
public class Experiment10Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 7000);
[Link]("Connected to server");
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader userIn = new BufferedReader(new
InputStreamReader([Link]));
String msg;
while (true) {
[Link]("Enter message: ");
msg = [Link]();
if ([Link]("exit")) break;
[Link](msg);
String response = [Link]();
[Link](response);
}
[Link]();
[Link]("Disconnected");
}
}
[CLIENT OUTPUT]:
Mahendra Mahara – BCA 6th
Experiment 11: Write a Java program that demonstrates secure client-server communication
using SSL. The program should implement a secure client socket with event handling, session
management in client mode, and a secure server socket using SSLServerSocket. It should
configure cipher suites, manage SSL sessions, and ensure encrypted message exchange between
client and server.
SOURCE CODE [SERVER]:
import [Link].*;
import [Link].*;
public class Experiment11Server {
public static void main(String[] args) throws Exception {
[Link]("[Link]", "[Link]");
[Link]("[Link]", "password");
SSLServerSocketFactory factory = (SSLServerSocketFactory)
[Link]();
SSLServerSocket server = (SSLServerSocket)
[Link](8443);
[Link]([Link]());
[Link]("SSL Server running on port 8443");
Mahendra Mahara – BCA 6th
while (true) {
SSLSocket socket = (SSLSocket) [Link]();
new Thread(() -> {
try (
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new
PrintWriter([Link](), true)
) {
String msg = [Link]();
[Link]("Client> " + msg);
[Link]("Server received: " + [Link]());
} catch (Exception e) {
[Link]();
}
}).start();
}
}
}
(Generate a keystore for the server:)
keytool -genkeypair -alias server -keyalg RSA -keysize 2048 -keystore [Link] -storepass
password -dname "CN=localhost"
(Export server certificate:)
keytool -exportcert -alias server -keystore [Link] -storepass password -file [Link]
OUTPUT:
Mahendra Mahara – BCA 6th
[CLIENT] :
import [Link].*;
import [Link].*;
public class Experiment11Client {
public static void main(String[] args) throws Exception {
[Link]("[Link]", "[Link]");
[Link]("[Link]", "password");
SSLSocketFactory factory = (SSLSocketFactory)
[Link]();
SSLSocket socket = (SSLSocket) [Link]("localhost",
8443);
[Link]([Link]());
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
[Link]("hello secure server");
String response = [Link]();
[Link]("Server> " + response);
[Link]();
}
}
(Import certificate into client truststore:)
keytool -importcert -alias server -file [Link] -keystore [Link] -storepass password -
noprompt
OUTPUT:
Mahendra Mahara – BCA 6th
Experiment 12: Write a Java program that demonstrates nonblocking I/O by implementing a
client and server using SocketChannel and ServerSocketChannel. The program should use buffers
to store and process data (creation, filling, draining, bulk operations, slicing, compacting,
duplicating, marking, and resetting), and handle data conversion. Implement readiness selection
with Selector and SelectionKey to manage multiple channels asynchronously, configure socket
options, and show how channels and buffers work together for efficient communication.
SOURCE CODE [NONBLOCKING I/O SERVER]:
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link].*;
public class Experiment12Server {
public static void main(String[] args) throws Exception {
ServerSocketChannel server = [Link]();
[Link](new InetSocketAddress("localhost", 6001));
[Link](false);
[Link]([Link].SO_REUSEADDR, true);
Selector selector = [Link]();
[Link](selector, SelectionKey.OP_ACCEPT);
[Link]("NIO Server running on port 6001");
while (true) {
[Link]();
Iterator<SelectionKey> it = [Link]().iterator();
Mahendra Mahara – BCA 6th
while ([Link]()) {
SelectionKey key = [Link]();
[Link]();
if ([Link]()) {
SocketChannel client = [Link]();
[Link](false);
[Link]([Link].TCP_NODELAY, true);
ByteBuffer buf = [Link](256);
[Link](selector, SelectionKey.OP_READ, buf);
[Link]("Client connected: " +
[Link]());
}
if ([Link]()) {
SocketChannel client = (SocketChannel) [Link]();
ByteBuffer buf = (ByteBuffer) [Link]();
int n = [Link](buf);
if (n == -1) {
[Link]();
[Link]("Client disconnected");
continue;
}
[Link]();
String msg = new String([Link](), 0, [Link]());
[Link]("Client> " + [Link]());
// Buffer operations demo
[Link]();
[Link](("Echo: " + [Link]()).getBytes());
[Link]();
[Link]("!".getBytes());
[Link]();
ByteBuffer dup = [Link]();
Mahendra Mahara – BCA 6th
ByteBuffer slice = [Link]();
[Link]();
[Link]();
[Link]();
[Link](buf);
[Link]();
}
}
}
}
}
[NONBLOCKING I/O SERVER] OUTPUT:
[NONBLOCKING I/O CLIENT] SOURCE:
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment12Client {
public static void main(String[] args) throws Exception {
SocketChannel client = [Link]();
[Link](false);
[Link]([Link].SO_KEEPALIVE, true);
Selector selector = [Link]();
Mahendra Mahara – BCA 6th
[Link](selector, SelectionKey.OP_CONNECT);
[Link](new InetSocketAddress("localhost", 6001));
while (true) {
[Link]();
Iterator<SelectionKey> it = [Link]().iterator();
while ([Link]()) {
SelectionKey key = [Link]();
[Link]();
if ([Link]()) {
if ([Link]()) {
[Link]("Connected to server");
ByteBuffer buf = [Link](256);
[Link](selector, SelectionKey.OP_WRITE,
buf);
}
}
if ([Link]()) {
ByteBuffer buf = (ByteBuffer) [Link]();
// buffer creation + fill
[Link]();
[Link]("hello nio server".getBytes());
// mark + reset + duplicate demo
[Link]();
[Link]("!".getBytes());
[Link]();
ByteBuffer dup = [Link]();
[Link]();
[Link]();
[Link](buf);
Mahendra Mahara – BCA 6th
[Link]();
[Link](selector, SelectionKey.OP_READ, buf);
}
if ([Link]()) {
ByteBuffer buf = (ByteBuffer) [Link]();
int n = [Link](buf);
if (n == -1) {
[Link]();
return;
}
[Link]();
byte[] data = new byte[[Link]()];
[Link](data); // bulk get
String msg = new String(data);
[Link]("Server> " + [Link]());
[Link]();
[Link]();
return;
}
}
}
}
}
[NONBLOCKING I/O CLIENT] OUTPUT:
Mahendra Mahara – BCA 6th
Experiment 13: Write a Java program that demonstrates the UDP protocol by implementing a
UDP client and server using DatagramSocket, DatagramPacket, and DatagramChannel. The
program should show how to construct packets, use getter and setter methods, send and receive
datagrams, manage connections, and configure socket options such as SO_TIMEOUT,
SO_RCVBUF, SO_SNDBUF, SO_REUSEADDR, SO_BROADCAST, and IP_TOS. Finally,
implement a simple UDP application such as an echo client-server to test communication.
SOURCE CODE [UDP SERVER]:
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment13Server {
public static void main(String[] args) throws Exception {
DatagramChannel channel = [Link]();
DatagramSocket socket = [Link]();
[Link](true);
[Link](true);
[Link](8192);
[Link](8192);
[Link](0x10); // IP_TOS
[Link](0);
[Link](new InetSocketAddress("localhost", 7001));
[Link]("UDP Echo Server running on port 7001");
ByteBuffer buf = [Link](1024);
while (true) {
[Link]();
SocketAddress clientAddr = [Link](buf);
[Link]();
String msg = new String([Link](), 0, [Link]());
[Link]("Client> " + [Link]());
[Link]();
Mahendra Mahara – BCA 6th
[Link](buf, clientAddr);
[Link]("Echoed back to " + clientAddr);
}
}
}
OUTPUT [UDP SERVER]:
SOURCE CODE [UDP CLIENT]:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment13Client {
public static void main(String[] args) throws Exception {
DatagramChannel channel = [Link]();
DatagramSocket socket = [Link]();
[Link](true);
[Link](true);
[Link](8192);
[Link](8192);
[Link](0x10); // IP_TOS
[Link](3000);
InetSocketAddress serverAddr = new InetSocketAddress("localhost",
7001);
[Link](serverAddr);
Mahendra Mahara – BCA 6th
BufferedReader userIn = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter message: ");
String msg = [Link]();
ByteBuffer buf = [Link]([Link]());
[Link](buf);
[Link]();
[Link](buf);
[Link]();
String reply = new String([Link](), 0, [Link]());
[Link]("Server> " + reply);
[Link]();
}
}
OUTPUT [UDP CLIENT]:
Experiment 14: Write a Java program that demonstrates IP multicasting by creating a multicast
client and server. The server should send messages to a multicast group using a MulticastSocket,
and the client should join the group, receive messages, and display them. Show how to construct
multicast sockets, work with multicast addresses and groups, and communicate with the group
effectively.
SOURCE CODE [SERVER]:
Mahendra Mahara – BCA 6th
import [Link].*;
import [Link].*;
public class Experiment14Server {
public static void main(String[] args) throws Exception {
String groupAddr = "[Link]"; // multicast group
int port = 4446;
MulticastSocket socket = new MulticastSocket();
InetAddress group = [Link](groupAddr);
[Link]("Multicast Server sending to " + groupAddr + ":" +
port);
BufferedReader userIn = new BufferedReader(new
InputStreamReader([Link]));
while (true) {
[Link]("Enter message (or 'exit'): ");
String msg = [Link]();
if ([Link]("exit")) break;
byte[] buf = [Link]();
DatagramPacket packet = new DatagramPacket(buf, [Link],
group, port);
[Link](packet);
[Link]("Sent: " + msg);
}
[Link]();
}
}
OUTPUT [SERVER]:
Mahendra Mahara – BCA 6th
SOURCE CODE [CLIENT]:
import [Link].*;
public class Experiment14Client {
public static void main(String[] args) throws Exception {
String groupAddr = "[Link]";
int port = 4446;
MulticastSocket socket = new MulticastSocket(port);
InetAddress group = [Link](groupAddr);
[Link](group);
[Link]("Multicast Client joined group " + groupAddr + ":"
+ port);
byte[] buf = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buf, [Link]);
[Link](packet);
String msg = new String([Link](), 0, [Link]());
[Link]("Received: " + msg);
}
}
}
Mahendra Mahara – BCA 6th
OUTPUT [CLIENT]:
Experiment 15: Write a Java program using Remote Method Invocation (RMI) where you
define and implement a remote service interface that provides a method to add two numbers.
Create an RMI server that registers this service and a client that invokes the remote method to
send two numbers to the server and display the result. Demonstrate running the complete RMI
system.
SOURCE CODE =>
[Remote Interface]:
import [Link].*;
public interface Experiment15Service extends Remote {
int add(int a, int b) throws RemoteException;
[Implementation]:
import [Link].*;
import [Link].*;
public class Experiment15ServiceImpl extends UnicastRemoteObject implements
Experiment15Service {
protected Experiment15ServiceImpl() throws RemoteException {
super();
}
public int add(int a, int b) throws RemoteException {
Mahendra Mahara – BCA 6th
return a + b;
}
}
[RMI Server]:
import [Link].*;
import [Link].*;
public class Experiment15Server {
public static void main(String[] args) {
try {
Experiment15Service service = new
Experiment15ServiceImpl();
[Link](1099);
[Link]("Experiment15Service", service);
[Link]("Experiment15Service registered and
running...");
} catch (Exception e) {
[Link]();
}
}
}
[RMI Client]:
import [Link].*;
import [Link].*;
public class Experiment15Client {
public static void main(String[] args) {
try {
Experiment15Service service = (Experiment15Service)
[Link]("rmi://localhost/Experiment15Service");
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
Mahendra Mahara – BCA 6th
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
int result = [Link](a, b);
[Link]("Result of " + a + " + " + b + " = " +
result);
} catch (Exception e) {
[Link]();
}
}
}
OUTPUT [SERVER]:
OUTPUT [CLIENT]:
Experiment 16: Write a Java program that connects to the website [Link] using
URL and URLConnection, retrieves the homepage content, prints its HTTP headers, guesses the
MIME type, and displays the first 200 characters of the page.
Mahendra Mahara – BCA 6th
SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment16 {
public static void main(String[] args) {
try {
URL url = new URL("[Link]
URLConnection conn = [Link]();
[Link]("---- HTTP Headers ----");
Map<String, List<String>> headers = [Link]();
for ([Link]<String, List<String>> e : [Link]()) {
[Link](([Link]() == null ? "" : [Link]() + ":
") + [Link]());
}
[Link]("\nMIME Type: " + [Link]());
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = [Link]()) != null && [Link]() < 200) {
[Link](line).append("\n");
}
[Link]();
[Link]("\n---- First 200 Characters of Page ----");
[Link]([Link](0, [Link](200, [Link]())));
} catch (Exception e) {
[Link]();
}
Mahendra Mahara – BCA 6th
}
}
OUTPUT:
Experiment 17: Write a Java program to implement a multi-client chat application where a
server accepts multiple client connections using sockets and each client can send messages that
are broadcast to all other connected clients in real time.
SOURCE CODE [SERVER]:
import [Link].*;
import [Link].*;
import [Link].*;
public class Experiment18Server {
private static Set<Socket> clients = [Link](new
HashSet<>());
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(6000);
[Link]("Chat Server running on port 6000...");
while (true) {
Socket client = [Link]();
Mahendra Mahara – BCA 6th
[Link](client);
[Link]("New client connected: " + client);
new Thread(() -> handleClient(client)).start();
}
}
private static void handleClient(Socket client) {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String msg;
while ((msg = [Link]()) != null) {
broadcast("Client " + [Link]() + ": " + msg, client);
}
} catch (IOException e) {
[Link]("Client disconnected: " + client);
} finally {
try { [Link](); } catch (IOException ignored) {}
[Link](client);
}
}
private static void broadcast(String msg, Socket sender) {
synchronized (clients) {
for (Socket c : clients) {
if (c != sender) {
try {
PrintWriter out = new
PrintWriter([Link](), true);
[Link](msg);
} catch (IOException ignored) {}
}
}
}
[Link](msg);
}
Mahendra Mahara – BCA 6th
}
OUTPUT [SERVER]:
SOURCE CODE [CLIENT 1]:
import [Link].*;
import [Link].*;
public class Experiment18Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 6000);
[Link]("Connected to chat server.");
new Thread(() -> {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String msg;
while ((msg = [Link]()) != null) {
[Link](msg);
}
} catch (IOException e) {
[Link]("Disconnected from server.");
}
}).start();
Mahendra Mahara – BCA 6th
BufferedReader userIn = new BufferedReader(new
InputStreamReader([Link]));
PrintWriter out = new PrintWriter([Link](), true);
String msg;
while ((msg = [Link]()) != null) {
[Link](msg);
}
}
}
OUTPUT [CLIENT 1]
SOURCE CODE [CLIENT 2]:
import [Link].*;
import [Link].*;
public class Experiment18Client2 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 6000);
[Link]("Connected to chat server.");
BufferedReader userIn = new BufferedReader(new
InputStreamReader([Link]));
PrintWriter out = new PrintWriter([Link](), true);
[Link]("Enter your name: ");
Mahendra Mahara – BCA 6th
String name = [Link]();
[Link](name + " joined the chat!");
new Thread(() -> {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String msg;
while ((msg = [Link]()) != null) {
[Link](msg);
}
} catch (IOException e) {
[Link]("Disconnected from server.");
}
}).start();
String msg;
while ((msg = [Link]()) != null) {
[Link](name + ": " + msg);
}
}
}
OUTPUT [CLIENT 1]:
Mahendra Mahara – BCA 6th