代码之家  ›  专栏  ›  技术社区  ›  static void main

使用RMI移动多个球时出现问题?

  •  0
  • static void main  · 技术社区  · 15 年前

    我正在用RMI制作一个移动球的分布式动画。

    我的目标是以某种方式移动多个球,以便多个客户观察到球的相同移动/位置,我使用的是远程对象Ball对象。

    当球只有一个的时候,它移动的很好,但是当我试图增加球的数量时,我失败了。

    下面是一些代码片段,我将循环应用于多个球:

    服务器上:

      b[0] = new BallImpl(0, 50, 2, 3 ,Color.YELLOW,20);
      b[1] = new BallImpl(50, 50, 4, 3,Color.BLUE,10);
      b[2] = new BallImpl(40, 40, 5, 5, Color.PINK,30);
      b[3] = new BallImpl(60, 70, 4, 6, Color.GREEN,40);
    
        for (int i = 0; i < currentNumBalls; i++) {
    
          Naming.rebind ("rmi://localhost/BouncingBall", b[i]);  // registers Ball object
          System.out.println ("remote ball object registered.");
        }
    

    客户现场:

    我如何寻找遥控球:

     for (int i = 0; i < currentNumBalls; i++) {
            try {
                this.aBall[i] = (Ball) Naming.lookup("rmi://localhost/BouncingBall");
    
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
        }
        start();    
    

    移动球代码:

    public void moveballs() {
    
            for (int i = 0; i < currentNumBalls; i++) {
                try {
    
                    aBall[i].setBounds(pit.getWidth(), pit.getHeight());
                    aBall[i].move();
    
                    pit.repaint();
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    

    这就是绘图代码:

     public void drawballs(Graphics g) {
    
        for (int i = 0; i < currentNumBalls; i++) {
            try {
    
                g.setColor(aBall[i].getColor());
                g.fillOval(aBall[i].getX(), aBall[i].getY(), aBall[i].getradius(), aBall[i].getradius());
    
            } catch (RemoteException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    有人能告诉我为什么我只能看到一个球在移动,其他球呢,或者在这个设计中有一些问题,我使用的RMI是错误的?或者给我推荐一些我可以实现目标的设计。

    谢谢,

    吉比

    1 回复  |  直到 15 年前
        1
  •  0
  •   dogbane    15 年前

    看起来你把所有的球都用同一个名字绑起来了。你需要给他们起不同的名字,比如:

    for (int i = 0; i < currentNumBalls; i++) {
    
      Naming.rebind ("rmi://localhost/BouncingBall"+i, b[i]); //add index to the name
      System.out.println ("remote ball object registered.");
    }
    

    然后在查找它们时,请使用:

     for (int i = 0; i < currentNumBalls; i++) {
        try {
            this.aBall[i] = (Ball) Naming.lookup("rmi://localhost/BouncingBall"+i);
    
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }