Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RMI notification from server to client on update

I'm writing a dummy shipping app. The client sends a product, and the server keeps all products that are sent.

Now the server - because it is just virtual - updates the state of the product every minute (SEND -> ACCEPTED -> SHIPPED -> RECEIVED), now i want the server to update the corresponding client when it has updated the state.

Most RMI information I fiend only talks about client -> server.. But i need my server to call my client for this one..

Hope you guys can help !

like image 299
Madsen Avatar asked Feb 21 '23 05:02

Madsen


1 Answers

Server to client communication is a bit of a minefield in all remoting technologies, including RMI. This is probably why you are struggling to find much documentation on the subject. For a dummy program in a controlled environment the following approach will work and is the simplest way to go. Note that all error handling has been omitted.

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

interface ClientRemote extends Remote {
    public void doSomething() throws RemoteException;
}

interface ServerRemote extends Remote {
    public void registerClient(ClientRemote client) throws RemoteException;
}

class Client implements ClientRemote {
    public Client() throws RemoteException {
        UnicastRemoteObject.exportObject(this, 0);
    }

    @Override
    public void doSomething() throws RemoteException {
        System.out.println("Server invoked doSomething()");
    }
}

class Server implements ServerRemote {
    private volatile ClientRemote client;

    public Server() throws RemoteException {
        UnicastRemoteObject.exportObject(this, 0);
    }

    @Override
    public void registerClient(ClientRemote client) throws RemoteException {
        this.client = client;
    }

    public void doSomethingOnClient() throws RemoteException {
        client.doSomething();
    }
}

Usage: Create a Server object on the server, add it to your RMI registry and look it up on the client.

There are other technologies that make client notifications easier, Java Message Service (JMS) is commonly used for this.

like image 167
Russ Hayward Avatar answered Mar 03 '23 06:03

Russ Hayward