Pergunta

i am programming a virtual network.
I have a central Client class which implements my whole network and allows to send/receive data to/from an specific other Client in the network. I now wan't to use a single instance of the Client class for ALL programs using the network. I have an interface for the programs to handle incoming packets, and a wrapper for sending, so I would appreciate another solution than "run a local TCP server".

My question now is: How can I have a single instance of a class running for all Programs using it in Java?

Foi útil?

Solução

This can be easily done by using RMI, RMI-IIOP or CORBA features that are available in Java. The mentioned technologies allow to create a single instance of object on a single machine (server) and export it to other computers (you say you need network) as a remote interface. In other hosts, you will have a stub class with the same interface your "real" instance implements, and will be able to call methods on it. These calls will be at the end remotely invoked on the single instance of your servant. To may opinion, this exactly that you are asking for.

From newer, more interesting approaches, Google Protocol Buffers looks like a good thing to look at, while you need more custom code with Protocol Buffers. Web services also allow to export the interface and are more suitable to pass through firewalls (other here listed approaches are more suitable for talking between your own servers you can configure how you want).

In case you need to ensure that only one instance of your program runs on a given operating system, this can be done as discussed in this question. If you program is listening on fixed ports, second instance probably will not start properly anyway as the ports are already taken; all you need is to catch exception when you try to bind the socked and terminate.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top