package de.tutorials.chat;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
public class Server extends Client implements ChatServer {
Map<String, ChatClient> clients = new ConcurrentHashMap<String, ChatClient>();
public Server() {
super("ChatServer");
}
public static void main(String[] args) throws Exception {
ChatServer chatServer = new Server();
Registry registry = LocateRegistry.createRegistry(CHAT_SERVER_PORT);
registry.bind(CHAT_SERVER_NAME, UnicastRemoteObject.exportObject(chatServer, 0));
System.out.println("Server ready...");
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
public void connect(ChatClient client) throws RemoteException {
clients.put(client.getName(), client);
super.receiveMessage(this, "Client connected: " + client.getName());
}
public void disconnect(ChatClient client) throws RemoteException {
clients.remove(client.getName());
super.receiveMessage(this, "Client disconnected: " + client.getName());
}
public void receiveMessage(ChatClient client, String message) throws RemoteException {
super.receiveMessage(client, message);
for (Map.Entry<String, ChatClient> chatClientEntry : clients.entrySet()) {
String clientName = chatClientEntry.getKey();
if (!clientName.equals(client.getName())) {
ChatClient chatClient = chatClientEntry.getValue();
chatClient.receiveMessage(client, message);
}
}
}
}