I am currently working on an assignment that deals with RMI. Essentially, it is just a chatroom. The problem that I am running into, though, is that I want to be able to get a username variable from my client, but that variable is not part of its remote interface:
public interface MulticastClient extends Remote {
public void deliver( MulticastClient sender, String channel,
Serializable message) throws RemoteException;
}
From what I understand, since sender is really a remote object, I can only access the methods and variables defined in the interface. Since this is a homework assignment I cannot change the interface (it was given to us).
Some code from my MulticastClient implementation:
public class ChatClient implements MulticastClient {
...
private String username;
@Override
public void deliver(MulticastClient sender, String channel,
Serializable message) throws RemoteException {
String senderName = ((ChatClient)sender).getUsername();
System.out.println("\r" + senderName + ": " + message.toString());
}
public String getUsername() {
return username;
}
...
public static void main(String[] args) throws Exception{
...
ChatClient client = new ChatClient();
MulticastClient stub = (MulticastClient)UnicastRemoteObject.exportObject(client, 0);
Registry reg = LocateRegistry.getRegistry(hostname, port);
MulticastService server = (MulticastService)reg.lookup(SERVER_NAME);
...
}
}
When I attempt to user the deliver method, as it is now, the error I get is:
Exception in thread "Thread-2" java.lang.ClassCastException: $Proxy0 cannot
be cast to csci4401.mc.ChatClient
I know that the cast in deliver() is causing the problem, but I am not sure what the correct way to do this is. Is there another way that I can get the ChatClient’s username?
What you can access remotely is defined by the remote interface, by definition. What you have at the client isn’t the remote object itself, it is a proxy for it that implements the same remote interface. Hence your exception.