📄 DateTimeClient.java
import java.net.*;
import java.util.Scanner;
public class DateTimeClient {
public static void main(String[] args) {
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Type 'getDateTime' to fetch date and time or 'exit' to quit: ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("Exiting client...");
break;
}
byte[] sendData = input.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(response);
}
clientSocket.close();
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
📄 DateTimeServer.java
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeServer {
public static void main(String[] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData;
System.out.println("DateTime Server started on port 9876...");
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String request = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received request: " + request);
String response;
if (request.equalsIgnoreCase("getDateTime")) {
// Format: dd-MM-yyyy HH:mm:ss
SimpleDateFormat formatter = new SimpleDateFormat("EEE,dd-MM-yyyy HH:mm:ss");
response = "Current Day, Date & Time: " + formatter.format(new Date());
} else {
response = "Invalid RPC call";
}
sendData = response.getBytes();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
📄 ClientCalc.java
import java.net.*;
import java.util.Scanner;
public class ClientCalc {
public static void main(String[] args) {
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter operation (e.g., add 5 10 (5 + 10) or 'exit'): ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("Client exiting...");
break;
}
byte[] sendData = input.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9000);
clientSocket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(response);
}
clientSocket.close();
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
📄 ServerCalc.java
import java.net.*;
public class ServerCalc{
public static void main(String args[]){
try{
DatagramSocket serverSocket = new DatagramSocket(9000);
byte[] receiveData = new byte[1024];
byte[] sendData;
System.out.println("Calculator Server is running on port 9000");
while(true){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String request = new String(receivePacket.getData(),0,receivePacket.getLength());
System.out.println("Received request: "+request);
String[] parts = request.split(" ");
String operation = parts[1];
int a = Integer.parseInt(parts[0]);
int b = Integer.parseInt(parts[2]);
int result=0;
switch(operation){
case "+":
result=a+b;
break;
case "-":
result=a-b;
break;
case "*":
result=a*b;
break;
case "%":
result=a%b;
break;
case "/":
result = (b!=0)?a/b:0;
break;
default:
result = 0;
}
String response = "Result: "+result;
sendData = response.getBytes();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,clientAddress,clientPort);
serverSocket.send(sendPacket);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
📄 TokenRing.java
package MutualExclusion;
import java.util.concurrent.atomic.AtomicBoolean;
public class TokenRing {
private static final int NUM_PROCESSES = 5;
private static AtomicBoolean[] hasToken = new AtomicBoolean[NUM_PROCESSES];
private static int currentTokenHolder = 0;
public static void main(String[] args) {
for (int i = 0; i < NUM_PROCESSES; i++) {
hasToken[i] = new AtomicBoolean(false);
}
hasToken[0].set(true);
for (int i = 0; i < NUM_PROCESSES; i++) {
int processId = i;
new Thread(() -> process(processId)).start();
}
}
private static void process(int processId) {
while (true) {
if (hasToken[processId].get()) {
// Enter critical section
System.out.println("Process " + processId + " is in the critical section.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Process " + processId + " is leaving the critical section.");
hasToken[processId].set(false);
currentTokenHolder = (processId + 1) % NUM_PROCESSES;
hasToken[currentTokenHolder].set(true);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
📄 BullyElection.java
package ElectionAlgorithm;
import java.util.ArrayList;
import java.util.List;
class Process {
int id;
boolean isAlive;
public Process(int id) {
this.id = id;
this.isAlive = true;
}
}
public class BullyElection {
private List<Process> processes;
private int coordinator;
public BullyElection(int[] processIds) {
processes = new ArrayList<>();
for (int id : processIds) {
processes.add(new Process(id));
}
coordinator = -1;
}
public void startElection(int initiatorId) {
System.out.println("Election started by Process " + initiatorId);
int newCoordinator = -1;
for (Process process : processes) {
if (process.isAlive && process.id > initiatorId) {
System.out.println("Process " + initiatorId + " sends election message to Process " + process.id);
newCoordinator = Math.max(newCoordinator, process.id);
}
}
if (newCoordinator == -1) {
coordinator = initiatorId;
System.out.println("Process " + initiatorId + " becomes the new Coordinator.");
} else {
System.out.println("Process " + newCoordinator + " will take over as Coordinator.");
startElection(newCoordinator);
}
}
public void killProcess(int processId) {
for (Process process : processes) {
if (process.id == processId) {
process.isAlive = false;
System.out.println("Process " + processId + " is now down.");
break;
}
}
}
public void printCoordinator() {
if (coordinator != -1) {
System.out.println("Current Coordinator: Process " + coordinator);
} else {
System.out.println("No Coordinator elected yet.");
}
}
public static void main(String[] args) {
int[] processIds = {1, 2, 3, 4, 5};
BullyElection election = new BullyElection(processIds);
election.startElection(2);
election.printCoordinator();
election.killProcess(5);
election.startElection(3);
election.printCoordinator();
}
}
📄 RingElection.java
import java.util.ArrayList;
import java.util.Collections;
public class RingElection {
static class Node {
int id;
boolean isActive;
Node(int id) {
this.id = id;
this.isActive = true;
}
}
public static void main(String[] args) {
ArrayList<Node> ring = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
ring.add(new Node(i));
}
ring.get(2).isActive = false;
int leaderId = startElection(ring);
System.out.println("Leader elected: Node " + leaderId);
}
public static int startElection(ArrayList<Node> ring) {
ArrayList<Integer> activeNodes = new ArrayList<>();
for (Node node : ring) {
if (node.isActive) {
activeNodes.add(node.id);
}
}
return Collections.max(activeNodes);
}
}
📄 ChatClient.java
import java.io.*;
import java.net.*;
public class ChatClient {
private static final String SERVER = "localhost";
private static final int PORT = 12345;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER, PORT);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Thread to receive messages from server
new Thread(() -> {
String serverMsg;
try {
while ((serverMsg = in.readLine()) != null) {
System.out.println(serverMsg);
}
} catch (IOException e) {
System.out.println("Connection closed.");
}
}).start();
// Main thread for sending messages to server
String inputMsg;
while ((inputMsg = userInput.readLine()) != null) {
out.println(inputMsg);
}
socket.close();
}
}
📄 ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private static final int PORT = 12345;
private static Set<ClientHandler> clientHandlers = new HashSet<>();
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Chat Server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getInetAddress());
ClientHandler clientHandler = new ClientHandler(clientSocket);
clientHandlers.add(clientHandler);
new Thread(clientHandler).start();
}
}
static void broadcast(String message, ClientHandler sender) {
for (ClientHandler client : clientHandlers) {
if (client != sender) {
client.sendMessage(message);
}
}
}
static class ClientHandler implements Runnable {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = in.readLine()) != null) {
System.out.println("Received: " + msg);
broadcast(msg, this);
}
} catch (IOException e) {
System.out.println("Client disconnected.");
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
clientHandlers.remove(this);
}
}
void sendMessage(String message) {
out.println(message);
}
}
}
📄 InitialsClient.java
import java.net.*;
import java.util.Scanner;
public class InitialsClient {
public static void main(String[] args) {
try {
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData;
byte[] receivedData = new byte[1024];
InetAddress add = InetAddress.getByName("localhost");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter your full name: ");
String data = sc.nextLine();
sendData = data.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,add,9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receivedData, receivedData.length);
clientSocket.receive(receivePacket);
String response = new String(receivePacket.getData(),0,receivePacket.getLength());
System.out.println(response);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
📄 InitialsServer.java
import java.net.*;
public class InitialsServer {
public static void main(String[] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receivedData = new byte[1024];
byte[] sendData;
while (true) {
DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
System.out.println("Server Started.");
serverSocket.receive(receivedPacket);
String response = new String(receivedPacket.getData(),0,receivedPacket.getLength());
System.out.println("Received Request: "+response);
String capName = response.toUpperCase();
String[] parts = capName.trim().split("\\s+");
StringBuilder initials = new StringBuilder();
for (String part : parts) {
if (!part.isEmpty())
initials.append(part.toUpperCase().charAt(0)).append(".");
}
String fullResult = "Your Name: "+ capName+ "\nYour Initials: "+ initials;
sendData = fullResult.getBytes();
InetAddress clientAdd = receivedPacket.getAddress();
int port = receivedPacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,clientAdd,port);
serverSocket.send(sendPacket);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
📄 Election.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Election {
private static final String MULTICAST_ADDRESS = "230.0.0.0";
private static final int PORT = 4446;
private static final int TOTAL_VOTES = 5;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
InetAddress group = InetAddress.getByName(MULTICAST_ADDRESS);
MulticastSocket socket = new MulticastSocket(PORT);
socket.joinGroup(group);
System.out.print("Enter your vote (A or B): ");
String vote = scanner.nextLine().toUpperCase();
if (!vote.equals("A") && !vote.equals("B")) {
System.out.println("Invalid vote.");
socket.close();
return;
}
byte[] voteBytes = vote.getBytes();
DatagramPacket packet = new DatagramPacket(voteBytes, voteBytes.length, group, PORT);
socket.send(packet);
System.out.println("Vote sent.");
new Thread(() -> {
try {
Map<String, Integer> voteCount = new HashMap<>();
voteCount.put("A", 0);
voteCount.put("B", 0);
int received = 0;
while (received < TOTAL_VOTES) {
byte[] buf = new byte[256];
DatagramPacket p = new DatagramPacket(buf, buf.length);
socket.receive(p);
String v = new String(p.getData(), 0, p.getLength()).toUpperCase();
if (v.equals("A") || v.equals("B")) {
voteCount.put(v, voteCount.get(v) + 1);
received++;
System.out.println("Received vote: " + v);
}
}
System.out.println("\nFinal Tally:");
System.out.println("A: " + voteCount.get("A"));
System.out.println("B: " + voteCount.get("B"));
if (voteCount.get("A") > voteCount.get("B")) {
System.out.println("Winner: A");
} else if (voteCount.get("B") > voteCount.get("A")) {
System.out.println("Winner: B");
} else {
System.out.println("It's a tie!");
}
socket.leaveGroup(group);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}