如何在同一接口方法上调用不同的远程对象并维护它们自己的数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (86)

我有一个服务器类,它实现了客户端和服务器之间的公共接口。我将多个远程对象绑定到不同的RIM注册表(diff端口和rim_id)。客户端将根据clientID查找注册表,例如,如果clientID是EXE 1111,那么它应该连接到EXE服务器远程对象。我希望每个服务器对象都有自己的hashtable来存储客户端提供的数据。以下是服务器代码:

enter code here
public class StationServers extends UnicastRemoteObject implements StationService{
    private static final long serialVersionUID = 8119533223378875144L;
    private String criminalRecordID="CR";
    private String missingRecordID="MR";
    private int count=11111;

    protected StationServers() throws RemoteException {
        super();
    }

    public static void main(String args[]){ 
            try {
                bindSPVMServer(new StationServers());
                bindSPLServer(new StationServers());
                bindSPBServer(new StationServers());

                System.out.print("Servers are up and running on ");
                System.out.println(InetAddress.getLocalHost().getHostName());
            } catch (Exception e) {
                System.err.println("Server start up error: "+e.getMessage());
                e.printStackTrace();
            }
    }

    private static void bindSPVMServer(StationServers spvmObject) {
        try {
            Registry reg = LocateRegistry.createRegistry(Constants.SPVM_RMI_PORT);
            reg.bind(Constants.SPVM_RMI_ID, spvmObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void bindSPLServer(StationServers splObject) {
        try {
            Registry reg = LocateRegistry.createRegistry(Constants.SPL_RMI_PORT);
            reg.bind(Constants.SPL_RMI_ID, splObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void bindSPBServer(StationServers spbObject) {
        try {
            Registry reg = LocateRegistry.createRegistry(Constants.SPB_RMI_PORT);
            reg.bind(Constants.SPB_RMI_ID, spbObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void createCRecord(String firstName, String lastName,
            String description, RecordStatus status) throws RemoteException {
    }

    @Override
    public void createMRecord(String firstName, String lastName,
            String address, String lastDate, String lastLocation,
            RecordStatus status) throws RemoteException {
        // TODO Auto-generated method stub

    }

    @Override
    public String getRecordCounts() throws RemoteException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void editCRecord(String lastName, String recordID,
            RecordStatus newStatus) throws RemoteException {
        // TODO Auto-generated method stub

    }

}

客户代码:

enter code here
public class OfficerClients implements Runnable{
    public static void showMenu() {
        System.out.println("\n****Welcome to DPIS****\n");
        System.out.println("Please select an option (1-5)");
        System.out.println("1. Create Criminal Record");
        System.out.println("2. Create Missing Record");
        System.out.println("3. Get Records Count");
        System.out.println("4. Edit Record");
        System.out.println("5. Exit");
    }

    public static void main(String[] args) {
        try {

            if (System.getSecurityManager() == null) 
                System.setSecurityManager(new RMISecurityManager());

            new Thread(new OfficerClients()).start();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static RecordStatus getRecordStatus(String status, int userChoice) {
        if (userChoice == 1) {
            if (RecordStatus.CAPTURED.name().equals(status))
                return RecordStatus.CAPTURED;
            else if (RecordStatus.ONTHERUN.name().equals(status))
                return RecordStatus.ONTHERUN;
            else
                throw new IllegalArgumentException("Invalid status for Criminal Record");
        } else if (userChoice == 2) {
            if (RecordStatus.FOUND.name().equals(status))
                return RecordStatus.FOUND;
            else if (RecordStatus.MISSING.name().equals(status))
                return RecordStatus.MISSING;
            else
                throw new IllegalArgumentException("Invalid status for Missing Record");
        } else if (userChoice == 3) {
            if (RecordStatus.CAPTURED.name().equals(status))
                return RecordStatus.CAPTURED;
            else if (RecordStatus.ONTHERUN.name().equals(status))
                return RecordStatus.ONTHERUN;
            else if (RecordStatus.FOUND.name().equals(status))
                return RecordStatus.FOUND;
            else if (RecordStatus.MISSING.name().equals(status))
                return RecordStatus.MISSING;
        }
        throw new IllegalArgumentException("No Enum specified for this string");
    }

    private static StationService getRemoteObjectStub(String stationName) {
        String url = "rmi://localhost:";
        Remote lookup = null;
        try {
            if ("SPVM".equals(stationName))
                url += Constants.SPVM_RMI_PORT;
            else if ("SPL".equals(stationName))
                url += Constants.SPL_RMI_PORT;
            else if ("SPB".equals(stationName))
                url += Constants.SPB_RMI_PORT;

            url += "/" + stationName;

            System.out.println("URL==" + url);

            if (url != null && !url.isEmpty())
                lookup = Naming.lookup(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (StationService) lookup;
    }

    @Override
    public void run() {
        int userChoice = 0;
        String firstName = "", lastName = "", description = "", address = "", lastDate = "", lastLocation = "", badgeID = "", recStatus = "", recordID = "";
        RecordStatus status;
        String requestBadgeID = "Please enter your unique BadgeID: ";
        String requestRecordID = "Please enter RecordID: ";
        String requestFName = "First Name: ";
        String requestLName = "Last Name: ";
        String requestDesc = "Description of Crime: ";
        String requestAddress = "Last Known Address: ";
        String requestDate = "Date last seen: ";
        String requestPlace = "Place last seen: ";
        String requestStatus = "Status: ";
        String requestNewStatus = "New Status: ";

        showMenu();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                System.in));
        try{

        while (true) {
            Boolean valid = false;

            System.out.print(requestBadgeID);
            badgeID = br.readLine().toUpperCase();
            System.out.println(badgeID);

            String stationName = badgeID.replaceAll("[0-9]", "").trim();
            System.out.println(stationName);
            StationService server = getRemoteObjectStub(stationName);

            while (!valid) {
                try {
                    System.out.print("Enter your choice: ");
                    userChoice = Integer.parseInt(br.readLine());
                    valid = true;
                } catch (Exception e) {
                    System.out
                            .println("Invalid Input, please enter an integer: ");
                    valid = false;
                }
            }

            switch (userChoice) {
            case 1:
                System.out.print(requestFName);
                firstName = br.readLine().trim().toUpperCase();
                System.out.print(requestLName);
                lastName = br.readLine().trim().toUpperCase();
                System.out.print(requestDesc);
                description = br.readLine().trim().toUpperCase();
                System.out.print(requestStatus);
                recStatus = br.readLine().trim().toUpperCase()
                        .replaceAll("\\s+", "");
                status = getRecordStatus(recStatus, userChoice);
                server.createCRecord(firstName, lastName, description,
                        status);
                showMenu();
                break;
            case 2:
                System.out.print(requestFName);
                firstName = br.readLine().trim().toUpperCase();
                System.out.print(requestLName);
                lastName = br.readLine().trim().toUpperCase();
                System.out.print(requestAddress);
                address = br.readLine().trim().toUpperCase();
                System.out.print(requestDate);
                lastDate = br.readLine().trim().toUpperCase();
                System.out.print(requestPlace);
                lastLocation = br.readLine().trim().toUpperCase();
                System.out.print(requestStatus);
                recStatus = br.readLine().trim().toUpperCase()
                        .replaceAll("\\s+", "");
                status = getRecordStatus(recStatus, userChoice);
                server.createMRecord(firstName, lastName, requestAddress,
                        lastDate, lastLocation, status);
                showMenu();
                break;
            case 3:
                String recordCounts = server.getRecordCounts();
                System.out.println(recordCounts);
                showMenu();
                break;
            case 4:
                System.out.print(requestLName);
                lastName = br.readLine().trim().toUpperCase();
                System.out.print(requestRecordID);
                recordID = br.readLine().trim().toUpperCase();
                System.out.print(requestNewStatus);
                recStatus = br.readLine().trim().toUpperCase()
                        .replaceAll("\\s+", "");
                status = getRecordStatus(recStatus, userChoice);
                server.editCRecord(lastName, recordID, status);
                showMenu();
                break;
            case 5:
                System.out.println("Have a nice day!");
                br.close();
                System.exit(0);
            default:
                System.out.println("Invalid Input, please try again.");
            }
        }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

我不知道如何维护每个远程对象,并基于客户端请求进行调用,将记录存储在hashtable中(每个远程对象)。

请帮忙!

提问于
用户回答回答于

只需创建远程对象的多个实例;将每个实例以不同的名称绑定到注册表中;让客户端在每次需要该特定实例时查找适当的名称;并通过该查找返回的存根并调用该方法。

扫码关注云+社区

领取腾讯云代金券