How is it not working? What is it doing that it shouldn't be (or what is it not doing that it should be)?
This increments the counter for each time the getIdentifier method is called. So if you had one client and you called getIdentifier 3 times, it would look like there were 3 different clients. It looks like you are also doing it in the constructor - so the getIdentifier would increment 4 times.
If you wanted to keep a count of how many times the ClientImpl was created, you want to keep a (private) static counter that you increment and store (as a private final) instance variable in the ClientImpl constructor. Something like this:
When do you create a second client? The code you provide creates exactly one Client, in the main method. It then creates a final hostName String that the actionPerformed method uses. So there is only 1 Client, and even if you had 2, since the same hostName String is being used, the new one will never be reflected in the output.
Unless when you mean you make a new client you mean running a second instance of the Java application.
If that is what you mean then you have a problem - variables, static or not, exist only in the scope of the local JVM. When you run the application a second time you get a new Virtual Machine, so the static variable counter gets re-initialized to 0.
You have to store the count in some location external to the JVM instance running. It helps that you are in a Client - Server scenario. When I have done things like this in the past (not using RMI though) I had the server tell the client which instance for that host as part of the registration process.
In my case, I had a handshake where the client connected to the server. The server received the client, checked the IP address for the client, and generated an ID. It then responded to the client with the ID, and to finish the handshake the client responded back to the server with the id.
Other means of doing the same thing might be to use a database, a file to store the current count of objects, or an external service (on the Client machine) listening on a socket that the client talks to to get the id.
I am not sure how RMI modifies these approaches...
Yes, I had a serverMain to register the server with RMI, and a clientMain to start a client and register it with the server.
I did not realize it was a separate JVM! Ugh. THANKS!!!
I was able to get it work in the manner I wished, by adding the static int counter to the serverImpl.
Every time a client registered with the server, I incremented the value and returned it, adding it to the hostname.
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop