我正在努力解决一个问题。我有客户端和服务器程序,我使用 RMI 在它们之间进行通信。
方法“connect”在客户端被调用,客户端将自己的引用作为参数传递给 stub.connect(this)
在connect(this)
方法中,服务器将this
(客户端引用)放在一个List 和一个HashMap 中。我检查过它们都已填充。
问题是当我稍后想在 Map 或 List 中查找引用时,this
似乎已更改。例如,我从客户端调用 move(this,direction)
,服务器在 map 和 hashmap 中都找不到关联的客户端。
这是 stub.connect(this)
调用代码:
public class Client extends JFrame implements KeyListener, IClient{
private IServer stub;
private Grid gameGrid;
public Client() throws AccessException, RemoteException, NotBoundException{
gameGrid = new Grid();
setTitle("Sweet collector game");
setSize(840, 560);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(gameGrid);
setVisible(true);
addKeyListener(this);
Registry registry = LocateRegistry.getRegistry(10000);
stub = (IServer) registry.lookup("IServer");
stub.connect(this);
}
服务器端连接方法:
public void connect(IClient c) throws RemoteException {
System.out.println("New player joined the game !");
this.currentPlayers.add(c);
Random rand = new Random();
Position2D<Integer,Integer> init = new Position2D<Integer,Integer>(rand.nextInt(gridsize-1),rand.nextInt(gridsize-1));
while(this.sweetsPosition.contains(init) || this.playersPosition.containsValue(init)){
init = new Position2D<Integer,Integer>(rand.nextInt(gridsize-1),rand.nextInt(gridsize-1));
}
this.playersPosition.put(c,init);
}
但是当我从同一个客户端调用 move(this,direction)
时,它无法在 list/map 中找到正确的对象:
public void move(int direction, IClient c) throws RemoteException {
if(this.playersPosition.containsKey(c)){ //always return FALSE for a reason I ignore
来自(显然是同一个)客户端的调用:
public void keyPressed(KeyEvent k) {
int keyCode = k.getKeyCode();
try {
stub.move(keyCode, this);
我希望我足够暴露我的问题。我真的需要你的帮助,我认为我无法独自解决这个问题......也许它甚至与 RMI 无关。
非常感谢。
最佳答案
每次您通过 RMI 传递 IClient
时,接收方都会收到不同的对象。除非 IClient
正确地实现了 equals()
和 hashCode()
,否则它不能用作 HashMap 键。
您还应该不通过序列化传递 JFrames。请参阅 Javadoc 以获取主要警告,无论如何它都没有意义。重构。
关于java - "this"将其作为参数传递给 RMI 时引用发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41417060/