Link to home
Start Free TrialLog in
Avatar of mtcmedia
mtcmedia

asked on

Simple RMI Example

Hello all,

I am having trouble getting a simple RMI program to run. I want to setup a client and a server on each machine, so that a client can query the opposing server and vice versa. It is a game of battlefields. Can someone please look at this code and let me know if it is wrong, or if it is because I am compiling it wrong. The error seems to be with the Naming.rebind in setupServer(). I have put hostnameinhere for now as the host names but they are setup right. The test classes, one calls attack() to start calling the remote lookup() method and the other waits for his turn using defend().


import java.rmi.*;
import java.rmi.server.*;

/* Sets up the Server and places object in RMI Registry */

public class Game extends UnicastRemoteObject implements RemoteGrid {
    final int X = 10;
    final int Y = 10;
    private String[] [] playerGrid = new String[X] [Y];
    final String miss = "MISS";
    final String hitA = "HIT AIRCRAFT CARRIER";
    final String hitB = "HIT BATTLESHIP";
    final String hitC = "HIT CRUISER";
    final String hitS = "HIT SUBMARINE";

    public Game() throws RemoteException {
        super();
    }

    public String lookup(int xCoord, int yCoord) {
        // lookup in here
        if (playerGrid[xCoord] [yCoord].equals("0")) {
            /* send miss */

            return miss;
        } else if (playerGrid[xCoord] [yCoord].equals("A")) {
             /* send HIT aircraft carrier */

            return hitA;
        } else if (playerGrid[xCoord] [yCoord].equals("C")) {
            /* send HIT cruiser */

            return hitC;
        } else if (playerGrid[xCoord] [yCoord].equals("B")) {
            /* send HIT battleship */

            return hitB;
        } else if (playerGrid[xCoord] [yCoord].equals("S")) {
            /* send HIT submarine */

            return hitS;
        } else {
            /* Error */

            System.out.println("Error");
            return "Error";
        }
    }
    // this should be main method
    public void setupServer(String[] [] getPlayerGrid) {
        playerGrid = getPlayerGrid;
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        String name = "//hostnameinhere/RemoteGrid";
        try {
            /* Setup a Game object */

            RemoteGrid theRemoteGrid = new Game();
            Naming.rebind(name, theRemoteGrid);
            System.out.println("Game bound");
        } catch (Exception e) {
            System.err.println("Game exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}


import java.rmi.*;
import java.math.*;

public class LocalGame {
    RemoteGrid opponentGrid = null;
    int winningCounter = 0;
    String FLAG = "";

    public void setupClient() {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        try {
            String name = "//hostnameinhere/RemoteGrid";
            RemoteGrid opponentGrid = (RemoteGrid) Naming.lookup(name);
            // call lookup in here on opponentGrid
        } catch (Exception e) {
            System.err.println("LocalGame exception: " +
                               e.getMessage());
            e.printStackTrace();
        }
    }

   // pass in grid
    public void attack(GridBuilder theGrid) {
        int[] shipCoords = new int[2];
        int x, y;
        shipCoords = theGrid.getCoords("SHOTCOORDS");
        x = shipCoords[0];
        y = shipCoords[1];
        String result = "";
        try {
            result = opponentGrid.lookup(x,y);
            FLAG = result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (result.equals("MISS")) {
                System.out.println("MISS!");
                defend(theGrid); // switch to defending
                } else {
                System.out.println("You HIT A " + result);
                winningCounter++;
                if (winningCounter == 50) {
                    System.out.println("YOU ARE THE BATTLESHIPS LEGEND!!!!!");
                    System.exit(0);
                }
                attack(theGrid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void defend(GridBuilder theGrid){
        while (!FLAG.equals("MISS")){
        }
        attack(theGrid);

    }

}


public class GameTest {
       public static void main(String[] args) {
        final int X = 10;
        final int Y = 10;
        String[] [] playerGrid = new String[X] [Y];
        GridBuilder theGrid = new GridBuilder();
        LocalGame localGame = new LocalGame();
        try {
            Game game = new Game();
            theGrid.initialseGrids(); // Initialise grids
            theGrid.addPlayerShips(); // Allow player to add ships to grid
            playerGrid = theGrid.getGrid(); // Get local copy of completed grid
            localGame.setupClient(); // Set up a client
            game.setupServer(playerGrid); // Set up a server with the local grid
            localGame.defend(theGrid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



public class GameTestTwo {
    public static void main(String[] args) {
        final int X = 10;
        final int Y = 10;
        String[] [] playerGrid = new String[X] [Y];
        GridBuilder theGrid = new GridBuilder();
        LocalGame localGame = new LocalGame();
        try {
            Game game = new Game();
            theGrid.initialseGrids(); // Initialise grids
            theGrid.addPlayerShips(); // Allow player to add ships to grid
            playerGrid = theGrid.getGrid(); // Get local copy of completed grid
            localGame.setupClient(); // Set up a client
            game.setupServer(playerGrid); // Set up a server with the local grid
            localGame.attack(theGrid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Avatar of Mayank S
Mayank S
Flag of India image

>> Can someone please look at this code and let me know if it is wrong, or if it is because I am compiling it wrong.

Do you get any errors while compiling? What errors and at what lines? And if you don't get any compilation errors but get exceptions while running, then pls tell us at which lines and what exceptions.

Make sure that you have starte the rmiregistry.exe before start the server application. rmiregistry muss know the server classpath.
Avatar of mtcmedia
mtcmedia

ASKER

This is what I have tried:

$ javac *.java
$ rmic Game
$ rmiregistry &

$java -Djava.rmi.server.codebase=http://urlinhere/~username/BattleShipsRMI/ GameTest


LocalGame exception: access denied (java.net.SocketPermission urlwasinhere resolve)
java.security.AccessControlException: access denied (java.net.SocketPermission urlwasinhere  resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkConnect(SecurityManager.java:1042)
        at java.net.InetAddress.getAllByName0(InetAddress.java:559)
        at java.net.InetAddress.getAllByName0(InetAddress.java:540)
        at java.net.InetAddress.getByName(InetAddress.java:449)
        at java.net.Socket.<init>(Socket.java:100)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:25)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:120)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:499)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:190)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:174)
        at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:318)
        at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
        at java.rmi.Naming.lookup(Naming.java:84)
        at LocalGame.setupClient(LocalGame.java:16)
        at GameTest.main(GameTest.java:22)
Game exception: access denied (java.net.SocketPermission urlwasinhere resolve)
java.security.AccessControlException: access denied (java.net.SocketPermission urlwasinhere resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkConnect(SecurityManager.java:1042)
        at java.net.InetAddress.getAllByName0(InetAddress.java:559)
        at java.net.InetAddress.getAllByName0(InetAddress.java:540)
        at java.net.InetAddress.getByName(InetAddress.java:449)
        at java.net.Socket.<init>(Socket.java:100)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:25)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:120)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:499)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:190)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:174)
        at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:318)
        at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
        at java.rmi.Naming.rebind(Naming.java:160)
        at Game.setupServer(Game.java:62)
        at GameTest.main(GameTest.java:23)

I have removed the actual server addresses with "urwasinhere" for security reasons.
Do you have a policy file?


-Check if the lastest stubs are present in http://urlinhere/~username/BattleShipsRMI/

-Try to run it without  -Djava.rmi.server.codebase=...
I dont have a policy file, and I put the stubs in another directory at as I though I had to do that?

http://urlinhere/~username/codebase/

you can try to replace you setSecurityManager with the follow:

if (System.getSecurityManager() == null) {      
      System.setSecurityManager(new RMISecurityManager() {
            public void checkConnect(String host, int port) {
            }
            public void checkConnect(String host, int port, Object context) {
            }
      });
}// if you use it then you not need policy files

What is the checkConnect method for? Its empty? Ill try keeping the stubs in http://urlinhere/~username/BattleShipsRMI/, and running without  -Djava.rmi.server.codebase

take a look at http://www.ccs.neu.edu/home/kenb/com3337/rmi_tut.html#secure


i have an rmi interface in my application. The difference is that i leave the stubs in the same directory as the server and client classes. it works without trouble. the only incovenience for me is to copy the stubs to client sides directory.
I just checked, and the stubs are in the correct directory, when I moved them I copied them, so they were still in the same directory as the server and client classes.

Do I have to copy the stubs myself to the client sides directory? If so, this will mean I have to do it both ways, and wont they have the same filenames and just overwrite?? eg Game_Stub.class and Game_Skel.class

I suggest: firstly try to run both, client and server, on the same mashine, with subs in same directory. Use above setSecurityManager and test again.
Where will I put your security manager?

Also, when I use rmic to generate the stubs, do I have to move them anywhere or do they just get left in the working directory?


in your code replace all
-----------------------------------------------------------------
 if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
  }
-----------------------------------------------------------------
with
-----------------------------------------------------------------
if (System.getSecurityManager() == null) {    
     System.setSecurityManager(new RMISecurityManager() {
          public void checkConnect(String host, int port) {
          }
          public void checkConnect(String host, int port, Object context) {
          }
     });
-----------------------------------------------------------------

i go home now, i see your posting tomorrow

When I run it, using the security manager you gave me in both places, and I also use "rmi://localhost/RemoteGrid", this is what happened:

$ java *.java
Exception in thread "main" java.lang.NoClassDefFoundError: Game/java
rmic Game
$ rmiregistry &
[1] 1715
$ java GameTest
NOTE: Please enter all coordinates in the form x,y!

Please enter a coordinate for your Aircraft Carrier:
0,0
Is the Aircraft Carrier facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Cruiser:
1,0
Is the Cruiser facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E
Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.

Please enter a coordinate for your Cruiser:
2,0
Is the Cruiser facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Cruiser:
3,0
Is the Cruiser facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
4,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
5,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
6,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Battleship:
7,0
Is the Battleship facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,0
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
9,0
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,2
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,4
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
8,6
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E

Please enter a coordinate for your Submarine:
9,2
Is the Submarine facing North N, South S, West W or East E:
Please Enter N, S, W or E:
E
All ships successfully added to grid.
Contacting other player to initiliase game.
 A A A A A 0 0 0 0 0
 0 A A A A A 0 0 0 0
 C C C C C C 0 0 0 0
 C C C C C C 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 S S S S S S S S 0 0
 S S S S 0 0 0 0 0 0
9,java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33042 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
Game bound
4java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33044 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33045 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33046 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33047 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33048 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33049 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
java.security.AccessControlException: access denied (java.net.SocketPermission 138.251.200.28:33050 accept,resolve)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
        at java.security.AccessController.checkPermission(AccessController.java:399)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkAccept(SecurityManager.java:1162)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.checkAcceptPermission(TCPTransport.java:567)
        at sun.rmi.transport.tcp.TCPTransport.checkAcceptPermission(TCPTransport.java:206)
        at sun.rmi.transport.Transport$1.run(Transport.java:151)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)
        at java.lang.Thread.run(Thread.java:484)
I had to cancel it as it kept on repeating those exceptions. Can anyone else help while junges is away?

Hi mtcmedia,

try to disable completely the  System.setSecurityManager(...) part.
I saw that i have do it because my jdbc connection security issues.
Looking on the Sun site, they say that you need to install a security manager. HELP!!!

Can someone try and run the code, and see if they can help?

i canot build it for tests
i missing the class GridBuilder
Sorry, here it is:

/* Generated by Together */

import java.io.*;
import java.util.*;

public class GridBuilder {
    /**
     * Value for the size of the grid. The number of rows in the grids.
     */
    final int X = 10;

    /**
     * Value for the size of the grid. The number of columns in the grids.
     */
    final int Y = 10;

        /* 2 x 2D Arrays for grids A[row][column] */

    /**
     * Grid data structure to hold the local player ships.
     */
    private String[] [] playerGrid = new String[X] [Y];

    /**
     * Grid data structure to hold the local player guesses.
     */
    private String[] [] guessGrid = new String[X] [Y];

    public String[] [] getGrid() {
        return playerGrid;
    }

        /** Initialise method to initialise two main data stuctures by filling with "0"'s. */
    public void initialseGrids() {
        /* Fill grids with 0's */

        for (int i = 0; i < X; i++) {
            for (int j = 0; j < Y; j++) {
                playerGrid[i] [j] = "0";
                guessGrid[i] [j] = "0";
            }
        }
    }

    /* Holder method allow user to place ships */

    /** Method to allow the player to place their ships on their local grid. */
    public void addPlayerShips() {
        System.out.println("NOTE: Please enter all coordinates in the form x,y!");
        String[] shipTypes = new String[4];
        int[] shipCoords = new int[2];
        String orientation = "";
        int x, y, count;
        shipTypes[0] = "Aircraft Carrier";
        shipTypes[1] = "Cruiser";
        shipTypes[2] = "Battleship";
        shipTypes[3] = "Submarine";

        /* Get Details For Aircraft Carrier And Add To Grid */

        shipCoords = getCoords(shipTypes[0]);
        x = shipCoords[0];
        y = shipCoords[1];
        orientation = getOrientation(shipTypes[0]);
        while (addACarrier(x, y, orientation) == false) { //if not added to grid successfully
            System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
            shipCoords = getCoords(shipTypes[0]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[0]);
        }

        /* Get Details For Other Ships And Add To Grid */

        /* Add Cruisers x 2 */

        for (int i = 0; i < 2; i++) {
            count = 6;
            shipCoords = getCoords(shipTypes[1]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[1]);
            while (addGenericShip(x, y, count, shipTypes[1], orientation) == false) {
                System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
                shipCoords = getCoords(shipTypes[1]);
                x = shipCoords[0];
                y = shipCoords[1];
                orientation = getOrientation(shipTypes[1]);
            }
        }

           /* Add Battleships x 4 */

        for (int i = 0; i < 4; i++) {
            count = 4;
            shipCoords = getCoords(shipTypes[2]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[2]);
            while (addGenericShip(x, y, count, shipTypes[2], orientation) == false) {
                System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
                shipCoords = getCoords(shipTypes[2]);
                x = shipCoords[0];
                y = shipCoords[1];
                orientation = getOrientation(shipTypes[2]);
            }
        }

                   /* Add Submarines x 6 */

        for (int i = 0; i < 6; i++) {
            count = 2;
            shipCoords = getCoords(shipTypes[3]);
            x = shipCoords[0];
            y = shipCoords[1];
            orientation = getOrientation(shipTypes[3]);
            while (addGenericShip(x, y, count, shipTypes[3], orientation) == false) {
                System.out.println("Sorry The Coordinates/Orientation You Entered Are Occupied/Out Of Range.");
                shipCoords = getCoords(shipTypes[3]);
                x = shipCoords[0];
                y = shipCoords[1];
                orientation = getOrientation(shipTypes[3]);
            }
        }
        System.out.println("All ships successfully added to grid.");
        System.out.println("Contacting other player to initiliase game.");
        printGrid();
    }

    /** Method to print out the current contents of the local grid. */
    public void printGrid() {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                System.out.print(" " + playerGrid[i] [j]);
            }
            System.out.println();
        }
    }

    /** Method to allow the user to enter coordinates. */
    public int[] getCoords(String shipType) {
        int[] shipCoords = new int[2];
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        int x = 0;
        int y = 0;
        char cX;
        char cY;
        System.out.println("");
        if (shipType.equals("SHOTCOORDS")) {
            try {
                System.out.println("Please enter a coordinate to fire at: ");
                str = in.readLine();
                cX = str.charAt(0);
                cY = str.charAt(2);
                x = (cX - 48);
                y = (cY - 48);
                shipCoords[0] = x;
                shipCoords[1] = y;
            } catch (IOException e) {
                System.out.println(e);
            }
            return shipCoords;
        } else {
            try {
                System.out.println("Please enter a coordinate for your " + shipType + ": ");
                str = in.readLine();
                cX = str.charAt(0);
                cY = str.charAt(2);
                x = (cX - 48);
                y = (cY - 48);
            } catch (IOException e) {
                System.out.println(e);
            }
            shipCoords[0] = x;
            shipCoords[1] = y;
            return shipCoords;
        }
    }

    /** Method to allow the user to enter an orientation. */
    public String getOrientation(String shipType) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        try {
            System.out.println("Is the " + shipType + " facing North N, South S, West W or East E: ");
            System.out.println("Please Enter N, S, W or E: ");
            str = in.readLine();
        } catch (IOException e) {
            System.out.println(e);
        }
        return str;
    }

        /* Generic Ship Placement */

    /** Generic add method to deal with adding all ship types (apart from Aircraft Carrier) to the local grid. */
    public boolean addGenericShip(int x, int y, int count, String shipType, String orientation) {
        int xPos = x;
        int yPos = y;
        int xPosC = x;
        int yPosC = y;
        if (orientation.equals("E")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC++;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                yPos++; // increment column
            }
            return true;
        } else if (orientation.equals("S")) {
                        /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                xPos++; // increment row
            }
            return true;
        } else if (orientation.equals("W")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC--;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                yPos--; // decerement column
            }
            return true;
        } else if (orientation.equals("N")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < count; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC--;
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < count; i++) {
                if (shipType.equals("Cruiser")) {
                    playerGrid[xPos] [yPos] = "C";
                } else if (shipType.equals("Battleship")) {
                    playerGrid[xPos] [yPos] = "B";
                } else if (shipType.equals("Submarine")) {
                    playerGrid[xPos] [yPos] = "S";
                }
                xPos--; // decrement row
            }
            return true;
        }
        return true;
    }

        /* Aircraft Carrier Placement */

    /** Method to allow the adding of an aircraft carrier to the local grid. */
    public boolean addACarrier(int x, int y, String orientation) {
        int xPos = x;
        int yPos = y;
        int xPosC = x;
        int yPosC = y;
        if (orientation.equals("E")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC++;
                } else {
                    return false;
                }
            }
            yPosC = y + 1; // increment column
            xPosC = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    yPosC++; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [yPos] = "A";
                yPos++; // increment column
            }
            yPos = y + 1; // increment column
            xPos = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                yPos++; // increment column
            }
            return true;
        } else if (orientation.equals("S")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++;
                } else {
                    return false;
                }
            }
            yPosC = y - 1; // derement column
            xPosC = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [xPos] = "A";
                xPos++; // increment row
            }
            yPos = y - 1; // derement column
            xPos = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                xPos++;
            }
            return true;
        } else if (orientation.equals("W")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++;
                } else {
                    return false;
                }
            }
            yPosC = y - 1; // derement column
            xPosC = x + 1; // increment row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC++; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                if (xPos <= 9 && xPos >= 0 && yPos <= 9 && yPos >= 0 && playerGrid[xPos] [yPos].equals("0")) {
                    yPos--;
                } else {
                    return false;
                }
            }
            yPos = y - 1; // derement column
            xPos = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                if (xPos <= 9 && xPos >= 0 && yPos <= 9 && yPos >= 0 && playerGrid[xPos] [yPos].equals("0")) {
                    yPos--; // increment column
                } else {
                    return false;
                }
            }
            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [xPos] = "A";
                yPos--; // decrement column
            }
            yPos = y - 1; // derement column
            xPos = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                yPos--;
            }
            return true;
        } else if (orientation.equals("N")) {
            /* First check all of the allocated coords are free */

            for (int i = 0; i < 5; i++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC--;
                } else {
                    return false;
                }
            }
            yPosC = y - 1; // increment column
            xPosC = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                if (xPosC <= 9 && xPosC >= 0 && yPosC <= 9 && yPosC >= 0 && playerGrid[xPosC] [yPosC].equals("0")) {
                    xPosC--; // increment column
                } else {
                    return false;
                }
            }

            /* Now place in the grid */

            for (int i = 0; i < 5; i++) {
                playerGrid[xPos] [xPos] = "A";
                xPos--; // decrement row
            }
            yPos = y - 1; // increment column
            xPos = x - 1; // decrement row
            for (int j = 0; j < 5; j++) {
                playerGrid[xPos] [yPos] = "A";
                xPos--;
            }
            return true;
        }
        return true;
    }



}

Hi mtcmedia, now it run without exceptions:

what is to do:

1- In the File GameTest i have changed the start order, firstly the server and then the client:
--->game.setupServer(playerGrid); // Set up a server with the local grid
--->localGame.setupClient(); // Set up a client

2- i used this setSecurityManager;
if (System.getSecurityManager() == null) {    
     System.setSecurityManager(new RMISecurityManager() {
          public void checkConnect(String host, int port) {
          }
          public void checkConnect(String host, int port, Object context) {
          }
     });
}


It runs, asking you to place your ships in the grid. But as soon as the RMI code starts then I get the same exceptions.

There are you files that i have used, i not understand why you continue receiving Exceptions.
ftp://200.102.160.107/mtcmedia.zip
Did you run the program, past the point where it asks you to place your ships in the grid?

I have typed exactly the same as you and this appears at the end:

All ships successfully added to grid.
Contacting other player to initiliase game.
 A A A A A 0 0 0 0 0
 0 A A A A A 0 0 0 0
 C C C C C C 0 0 0 0
 C C C C C C 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 B B B B 0 0 0 0 0 0
 S S S S S S S S 0 0
 S S S S 0 0 0 0 0 0
Game bound

I not understand what is this, but it works without exception.


The last question is, is there a way I can test if the server is ready before setting up the client? For example I want to check the remote server grid is ready before I set up my client and try to bind to the remote object. How do I do this?
I know I could setup a Socket to send a message when the server is ready for clients, but doesnt RMI have a function to do this?
ASKER CERTIFIED SOLUTION
Avatar of Daniel Junges
Daniel Junges
Flag of Brazil image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I like that idea, good I will do that.

So are you sure that the game works? Does it let you take a guess at the opponent grid, and print out "HIT" or "MISS"?

hi mtcmedia, i dont know if it works because i self not know how to play with it correctly :-)