Practical one RCP (Remote Procedure Call).
Client join server and sending messages.
//Client.java
public class Client {
private static final String HOST = "127.0.0.1";
private static final int PORT = 12345;
public static void main(String[] args) {
try (
Socket socket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Scanner scanner = new Scanner(System.in)
) {
System.out.println("Connected to chat server");
new Thread(() -> {
String message;
try {
while ((message = in.readLine()) != null) {
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
System.out.print("Enter your name: ");
do {
out.println(scanner.nextLine());
} while (scanner.hasNextLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server.java
public class Server {
private static final int PORT = 12345;
private static Set<ClientHandler> clientHandlers = new HashSet<>();
public static void main(String[] args) {
System.out.println("Server is started...");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
ClientHandler clientHandler = new ClientHandler(clientSocket);
clientHandlers.add(clientHandler);
clientHandler.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void broadcast(String message, ClientHandler sourceClient) {
for (ClientHandler clientHandler : clientHandlers) {
if (clientHandler != sourceClient) {
clientHandler.sendMessage(message);
}
}
}
private static class ClientHandler extends Thread {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
private String name;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Enter your name:");
name = in.readLine();
System.out.println(name + " has joined chat-room.");
broadcast(name + " has joined chat-room.", this);
String message;
while ((message = in.readLine()) != null) {
System.out.println(name + ": " + message);
broadcast(name + ": " + message, this);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
cleanup();
}
}
private void cleanup() {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (clientSocket != null) {
clientSocket.close();
}
clientHandlers.remove(this);
System.out.println(name + " has left the chat-room.");
broadcast(name + " has left the chat-room.", this);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(String message) {
if (out != null) {
out.println(message);
}
}
}
}
A: a) Implement a Server calculator containing ADD(),MUL(),SUB() etc.
Client.java
package practical_2;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Client {
private static final int PORT = 1234;
private static final int BUFFER_SIZE = 65535;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getLocalHost();
while (true) {
System.out.print(
"Enter the equation in the format 'operand operator operand' (e.g., 5 + 3) or type 'bye' to exit: ");
String inp = sc.nextLine().trim();
if (inp.equalsIgnoreCase("bye")) {
sendPacket(ds, ip, "close", PORT);
break;
}
sendPacket(ds, ip, inp, PORT);
String response = receivePacket(ds);
System.out.println("Answer = " + response.trim());
}
ds.close();
sc.close();
}
private static void sendPacket(DatagramSocket ds, InetAddress ip, String message, int port)
throws IOException {
byte[] buf = message.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, port);
ds.send(packet);
}
private static String receivePacket(DatagramSocket ds) throws IOException {
byte[] buf = new byte[BUFFER_SIZE];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ds.receive(packet);
return new String(packet.getData(), 0, packet.getLength());
}
}
Server.java
package practical_2;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.StringTokenizer;
public class Server {
private static final int PORT = 1234;
private static final int BUFFER_SIZE = 65535;
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(PORT);
System.out.println("Server started. Waiting for client messages...");
while (true) {
DatagramPacket receivedPacket = receivePacket(ds);
String receivedMessage = new String(receivedPacket.getData(), 0,
receivedPacket.getLength()).trim();
int clientPort = receivedPacket.getPort();
InetAddress clientAddress = receivedPacket.getAddress();
if (receivedMessage.equalsIgnoreCase("close")) {
System.out.println("Client sent closing request. Shutting down server.");
break;
}
System.out.println("Equation Received: " + receivedMessage);
String result = processEquation(receivedMessage);
System.out.println("Sending result: " + result);
sendPacket(ds, result, clientAddress, clientPort);
}
ds.close();
}
private static DatagramPacket receivePacket(DatagramSocket ds) throws IOException {
byte[] buf = new byte[BUFFER_SIZE];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ds.receive(packet);
return packet;
}
private static void sendPacket(DatagramSocket ds, String message, InetAddress address, int port)
throws IOException {
byte[] buf = message.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
ds.send(packet);
}
private static String processEquation(String equation) {
try {
StringTokenizer st = new StringTokenizer(equation);
int operand1 = Integer.parseInt(st.nextToken());
String operator = st.nextToken();
int operand2 = Integer.parseInt(st.nextToken());
int result;
switch (operator) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
result = operand2 != 0 ? operand1 / operand2 : 0;
break;
case "%":
result = operand1 % operand2;
break;
default:
System.out.println("Invalid operation received.");
return "Error: Invalid operation";
}
return Integer.toString(result);
} catch (Exception e) {
return "Error: Invalid input format";
}
}
}
B) Implementation of Remote Procedure Call Concept using datagram: This application will demonstrate the remote procedure communication
//Server.java
package practical_2.b;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.StringTokenizer;
public class Server {
private static final int SERVER_PORT = 1200;
private static final int CLIENT_PORT = 1300;
private static final int BUFFER_SIZE = 4096;
private DatagramSocket socket;
public Server() {
try {
socket = new DatagramSocket(SERVER_PORT);
System.out.println("RPC Server Started...");
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
DatagramPacket requestPacket = receiveRequest(buffer);
String clientMessage = new String(requestPacket.getData(), 0,
requestPacket.getLength()).trim();
if ("q".equalsIgnoreCase(clientMessage)) {
System.out.println("Exit command received. Shutting down server.");
break;
}
String response = processRequest(clientMessage);
sendResponse(response, requestPacket.getAddress());
System.out.println("Response sent: " + response + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}
private DatagramPacket receiveRequest(byte[] buffer) throws Exception {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
return packet;
}
private String processRequest(String message) {
StringTokenizer tokenizer = new StringTokenizer(message, " ");
if (!tokenizer.hasMoreTokens()) {
return "Error: No command received.";
}
String command = tokenizer.nextToken();
switch (command.toLowerCase()) {
case "date":
return getCurrentDate();
case "time":
return getCurrentTime();
default:
return "Error: Unknown command '" + command + "'";
}
}
private void sendResponse(String response, InetAddress clientAddress) throws Exception {
byte[] responseData = response.getBytes();
DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length,
clientAddress, CLIENT_PORT);
socket.send(responsePacket);
}
private String getCurrentDate() {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
return LocalDateTime.now().format(dateFormatter);
}
private String getCurrentTime() {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
return LocalDateTime.now().format(timeFormatter);
}
public static void main(String[] args) {
new Server();
}
}
Client.java
package practical_2.b;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
private static final int SERVER_PORT = 1200;
private static final int CLIENT_PORT = 1300;
private static final int BUFFER_SIZE = 50;
private DatagramSocket socket;
private InetAddress serverAddress;
public Client() {
try {
socket = new DatagramSocket(CLIENT_PORT);
serverAddress = InetAddress.getLocalHost();
System.out.println("RPC Client Started\n");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter message (or 'exit' to quit): ");
String message = inputReader.readLine();
if ("exit".equalsIgnoreCase(message)) {
System.out.println("Exiting...");
break;
}
sendMessage(message);
String response = receiveMessage();
System.out.println("Result = " + response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}
private void sendMessage(String message) throws Exception {
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, serverAddress, SERVER_PORT);
socket.send(packet);
}
private String receiveMessage() throws Exception {
byte[] buffer = new byte[BUFFER_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
return new String(packet.getData(), 0, packet.getLength()).trim();
}
public static void main(String[] args) {
new Client();
}
}
- Practical
//DateTimeServer.java
package practical_3;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeServer extends UnicastRemoteObject implements DateTime {
protected DateTimeServer() throws RemoteException {
super();
}
@Override
public String getDateTime(int option) throws RemoteException {
Date date = new Date();
SimpleDateFormat formatter;
if (option == 1) {
formatter = new SimpleDateFormat("MM/dd/yyyy");
return formatter.format(date);
} else if (option == 2) {
formatter = new SimpleDateFormat("HH:mm:ss");
return formatter.format(date);
}
return "Invalid option";
}
public static void main(String[] args) {
try {
DateTimeServer server = new DateTimeServer();
Naming.rebind("rmi://localhost:1099/DateTimeService", server);
System.out.println("DateTime Service is running...");
} catch (Exception e) {
System.out.println("Server error: " + e);
}
}
}
//DateTime (interface)
public interface DateTime extends Remote {
String getDateTime(int option) throws RemoteException;
}
//DateTimeClient
public class DateTimeClient {
public static void main(String[] args) {
try {
DateTime stub = (DateTime) Naming.lookup("rmi://localhost:1099/DateTimeService");
System.out.println("Current Date: " + stub.getDateTime(1));
System.out.println("Current Time: " + stub.getDateTime(2));
} catch (Exception e) {
System.out.println("Client error: " + e);
}
}
}