EX3 RMI - Docx-1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Exercise 3

Program to demonstrate Remote Method Invocation in Java.


ChatClient.java

import java.rmi.Naming;
import java.util.Scanner;

public class ChatClient {


public static void main(String[] args) {
try {
ChatInterface server = (ChatInterface) Naming.lookup("rmi://localhost/chat");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
server.sendMessage(name + " joined the chat.");

while (true) {
System.out.print("You: ");
String message = scanner.nextLine();
server.sendMessage(name + ": " + message);
}
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}

ChatInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface ChatInterface extends Remote {


void sendMessage(String message) throws RemoteException;
void receiveMessage(String message) throws RemoteException;
}
ChatServer.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

public class ChatServer extends UnicastRemoteObject implements ChatInterface {


private final List<ChatInterface> clients;

protected ChatServer() throws RemoteException {


clients = new ArrayList<>();
}

@Override
public synchronized void sendMessage(String message) throws RemoteException {
System.out.println("Received message: " + message);
for (ChatInterface client : clients) {
client.receiveMessage(message);
}
}

public synchronized void addClient(ChatInterface client) {


clients.add(client);
}

public static void main(String[] args) {


try {
ChatServer server = new ChatServer();
java.rmi.registry.LocateRegistry.createRegistry(1098);
java.rmi.registry.Registry registry = java.rmi.registry.LocateRegistry.getRegistry();
registry.rebind("chat", server);
System.out.println("Server started");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
@Override
public void receiveMessage(String message) throws RemoteException {
System.out.println("Received message: " + message);
}
}

You might also like