【问题标题】:Problem moving multiple balls with RMI?使用 RMI 移动多个球时出现问题?
【发布时间】:2010-10-16 21:50:09
【问题描述】:

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

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

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

这里有一些代码 sn-ps,我在其中应用循环来处理多个球:

在服务器上:

  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?或者向我推荐一些可以实现我的目标的设计。

非常感谢,

吉比

【问题讨论】:

    标签: java animation client-server distributed rmi


    【解决方案1】:

    看起来您将所有球都绑定在同一个名称下。您需要给它们起不同的名称,如下所示:

    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);
        }
    }
    

    【讨论】:

    • 啊,我的假设是错误的,我认为这不是有效的方法,你能想到任何其他方法来完成这项任务。
    猜你喜欢
    • 2014-06-06
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多