Object passed to RMI Server

Hello
I have a function in the RMI client that passes an object to the RMI server. The server updates one of the members of this object.
When I try to get this memebr from the client, I get 0.
This is the Object code:
public class Progress implements Serializable {
          private static final long     serialVersionUID     = 8168473416653301292L;
                    private int mProgress = 0;
    /** Creates a new instance of Progress */
    public Progress() {
    public int getProgress()
        return mProgress;
    public void setProgress(int progress)
              System.out.println("progress = "+progress);
        mProgress = progress;
}This is the function that passes the Object to the server:
          public RequestResult executeAdminAPI(int aDbTypeOrdinal, String aHost, int aPort, String aUser, String aPassword,
                              String aInput, Progress progress) throws RMIClientException, SCException {
                    try {
                              if (mServerInitialised)
                                        return mJNICommRMIServer.executeAdminAPIWrapper(aDbTypeOrdinal, aHost, aPort, aUser, aPassword, aInput, progress);
                              else {
                                        synchronized (mServerInitializedMutex) {
                                                  return mJNICommRMIServer.executeAdminAPIWrapper(aDbTypeOrdinal, aHost, aPort, aUser, aPassword, aInput, progress);
                    catch (RemoteException e) {
                              // We'll restart the server on JNIFatalException
                              // means that we should kill the process and restart it
                              // JNIFatalException means that the cpp code send an error code which
                              // We don't restart the server on SocketTimeOut like the other functions,
                              // because this function may take a long time to execute
                              if (e.detail instanceof JNIFatalException) {
                                        restartServer("executeAdminAPI got an exception: " + e.detail.getMessage());
                              if ((e.detail instanceof ConnectException)) // RMI-TODO check perhaps it
                                        // should be restartServer()
                                        startServer("executeAdminAPI got an exception: " + e.detail.getMessage());
                              if (e.detail instanceof JNIException)
                                        throw new SCException(((JNIException) (e.detail)).getErrorCode(), ((JNIException) (e.detail)).getErrorMessage());
                              else
                                        throw new RMIClientException(e);
          }The "setProgress" (called by the server) prints the correct numbers, but the "getProgress" (called by the client) returns 0.
Can anyone explain please?
Thanks,
Libby

Arguments are passed by value in RMI unless they are exported remote objects. So the update took place at the server only. If you want it reflected at the client, either (i) return the updated object as the result of the method, or (ii) make the updatable object an exported remote object, i.e. a callback. But note that (ii) doesn't play with firewals in place.

Similar Messages

  • Objects passed over RMI?

    When passing a serializable object over RMI (such as an ArrayList) which contains other objects, do the objects contained within this object (e.g. within the ArrayList) need to be serializable also?

    RMI server is very easy, if you want to make clear
    about this problem .
    you must read two interface . RemoteCall , RemoteRef
    Socket clientSecket = new Socket(RemoteHost ,port);
    OutputStream outputStream = clientSecket
    .getoutputStream();
    ObjectOutputStream out = new
    ObjectOutputStream(outputStream)
    out.write(Object);//
    then send a Object to server. if the object not be
    implements java.io.Serialisize , Exception will
    throw.
    are you clear ????? Sha BI ! !!!!!!Are you clear? RMI servers are much simpler than this, and you certainly don't need to know anything about either the RemoteCall or the RemoteRef interface. All this is done behind the scenes for you in RMI, just do call and return. Everyything passed or returned must be serializable, otherwise you get a NotSerializableException.

  • RMI-server communicates oracle: Exception

    Hallo everybody,
    My task is:
    - to implement in oracle Java stored procedure,
    - to implement RMI server
    - to load in oracle wrapper for Connection-object (ConnectionImpl), that has a reference at Connection (default oracle Connection), this ConnectionImpl-object will be passed to RMI-server, the RMI-server will call a method on this object.
    - Stub and Skeleton of ConnectionImpl are on both sides available (inside of oracle (as .jar) and on RMI-server side).
    First I start RMI-server. Then I call the stored procedure. It finds RMI-server, calls the method on RMI-server side, then RMI-server tries to call the method of ConnectionImpl with the following result:
    Fehler: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
         java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
         java.net.SocketException: Connection reset
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
         java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
         java.net.SocketException: Connection reset
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
         java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
         java.net.SocketException: Connection reset
         at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:292)
         at sun.rmi.transport.Transport$1.run(Transport.java:148)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.rmi.transport.Transport.serviceCall(Transport.java:144)
         at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:460)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:701)
         at java.lang.Thread.run(Thread.java:534)
         at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:247)
         at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:223)
         at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:133)
         at server.NativeDllServer_Stub.init(Unknown Source)
         at storedprocedure.OracleTest.verbinde(OracleTest:26)
    Caused by: java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
         java.net.SocketException: Connection reset
         at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:274)
         at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:171)
         at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:101)
         at elena.ConnectionImpl_Stub.returnString(Unknown Source)
         at server.NativeDllServer.init(NativeDllServer.java:18)
    I will be thankful for every tip, how I can resolve it.

    Its clear you have the java permission set to allow db Java to write to a socket, since the call to the RMI server works, but maybe you are missing the permission to allow db java to listen and/or read from a socket?
    See:
    http://download-west.oracle.com/docs/cd/B14117_01/java.101/b12021/security.htm#sthref714
    for java.net.SocketPermission
    Chris

  • RMI Server Object Startup Error

    Greetings,
    I am trying to set up a computer lab at my college. I currently have one server running Slackware 9.1 and one client (my laptop) running Windows XP Home. I can telnet and ftp from my client. I can also access the Apache web server running on the Linux machine. I recently discovered RMI as a way to do distributed computing (we are trying to build a proof-of-concept distributed computing system). However, I cannot get RMI to work. When I take the code I wrote and use my laptop as both client and server, everything works. However, when I try to use both machines, it does not work. I want the Linux box to be the server and my laptop to be the client. After compiling my RMI server class (the class that registers the server object for use under RMI) and running it by typing java RemServer, I get a strange error (see bottom of this message). I cannot find this error anywhere else on the internet. I have the rmiregistry program running. I do everything the same as when I do RMI on just my laptop. Please help!
    RemServer Remote Exception: java.rmi.UnmarshalException: Error unmarshaling return; nested exception is:
    java.net.SocketException: Connection reset
    [Ljava.lang.StackTraceElement;@13d93f4
    Thanks,
    Jason

    One thing I did discover is that I have not been explicitly starting rmid. Some documentation says that rmi starts rmid automatically. If I need to start rmid, what parameters to I need to pass to it?
    Thanks,
    Jason

  • RMI server object lookup in a session bean

    Hi all,
    I am getting MarshalException when I call java.rmi.Naming.lookup() in a session
    bean. Following is the code and exception. Please note that I am using java.rmi
    package instead of weblogic.rmi and that both the session bean and RMI server
    object (a startup class) is deployed on the same machine.
    Thanks for your help in advance.
    // a simple, replica-aware session bean method
    // some code here
    try {
    MediatorInterface mediator = (MediatorInterface) java.rmi.Naming.lookup("rmi://localhost:7001/TestMediator);
    catch (Exception e) {
    // log the exception
    The exception:
    java.rmi.MarshalException: Error marshaling transport header; nested exception
    i
    s:
    java.io.EOFException
    java.io.EOFException
    at java.io.DataInputStream.readByte(DataInputStream.java:224)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:206
    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 test.mgmtop.CreateNetworkOpHandler.execute(CreateNetworkOpHandler.jav
    a:88)
    at test.mgmtop.CreateNetworkOpHandler.perform(CreateNetworkOpHandler.jav
    a:28)
    at test.ejb.MgmtServiceBean.create(MgmtServiceBean.java:57)
    at test.ejb.MgmtServiceSession_idi8yo_EOImpl.create(MgmtServiceSession_i
    di8yo_EOImpl.java:46)
    at test.ejb.MgmtServiceSession_idi8yo_EOImpl_WLSkel.invoke(Unknown Sourc
    e)
    at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:346)
    at weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerR
    ef.java:114)
    at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:300)
    at weblogic.security.service.SecurityServiceManager.runAs(SecurityServic
    eManager.java:762)
    at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.jav
    a:295)
    at weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest
    .java:30)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:152)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:133)

    Hi Pyung,
    How about trying this instead:
    InitialContext ctx = new InitialContext();
    MediatorInterface mediator = (MediatorInterface) ctx.lookup("TestMediator");
    This assumes your startup class binds the Mediator to the JNDI name "TestMediator".
    - Matt
    Pyung Yoon wrote:
    Hi all,
    I am getting MarshalException when I call java.rmi.Naming.lookup() in a session
    bean. Following is the code and exception. Please note that I am using java.rmi
    package instead of weblogic.rmi and that both the session bean and RMI server
    object (a startup class) is deployed on the same machine.
    Thanks for your help in advance.
    // a simple, replica-aware session bean method
    // some code here
    try {
    MediatorInterface mediator = (MediatorInterface) java.rmi.Naming.lookup("rmi://localhost:7001/TestMediator);
    catch (Exception e) {
    // log the exception
    The exception:
    java.rmi.MarshalException: Error marshaling transport header; nested exception
    i
    s:
    java.io.EOFException
    java.io.EOFException
    at java.io.DataInputStream.readByte(DataInputStream.java:224)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:206
    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 test.mgmtop.CreateNetworkOpHandler.execute(CreateNetworkOpHandler.jav
    a:88)
    at test.mgmtop.CreateNetworkOpHandler.perform(CreateNetworkOpHandler.jav
    a:28)
    at test.ejb.MgmtServiceBean.create(MgmtServiceBean.java:57)
    at test.ejb.MgmtServiceSession_idi8yo_EOImpl.create(MgmtServiceSession_i
    di8yo_EOImpl.java:46)
    at test.ejb.MgmtServiceSession_idi8yo_EOImpl_WLSkel.invoke(Unknown Sourc
    e)
    at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:346)
    at weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerR
    ef.java:114)
    at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:300)
    at weblogic.security.service.SecurityServiceManager.runAs(SecurityServic
    eManager.java:762)
    at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.jav
    a:295)
    at weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest
    java:30)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:152)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:133)

  • Error passing a remote object in a rmi function call

    Hi,
    I've a problem passing an UnicastRemoteObject extended object in a rmi function call. I get the following error
    java.lang.IllegalArgumentException: argument type mismatch
    I've 2 Remote Objects: GalaxyRegistration and Station. I want to pass a Station Object as argument in a function from GalaxyRegistration. Does anyone know what the problem is?
    Here is the code:
    public class GalaxyRegistration
    extends UnicastRemoteObject
    implements GalaxyRegistrationInterface, Galaxy {
         public GalaxyRegistration() throws RemoteException {
         public void add(Station station) throws RemoteException {
              stations.addElement(station);
              System.out.println("Add Station " + station.getName());
    public class Station
    extends UnicastRemoteObject
    implements StationInterface {
         SystemInfo system;
         public Station(String name, String description, Coordinate position, Profile profile)
    throws RemoteException {
              system = new SystemInfo(name, description, position, profile);
    public class StationServer {
         Station station;
         public void run() {
              // create new Station
              System.out.println("Create new Station:");
              // register and bind new station
              try     {
                   station = new Station(name, descr, location, profile);
                   System.out.println("Station created ...");
                   GalaxyRegistrationInterface registry =
                             (GalaxyRegistrationInterface)
                             Naming.lookup
    ("//localhost/GalaxyRegistration");
                   System.out.println("Registry looked up ...");               
                   // >>>>>>>> NEXT LINE IS THE ERROR LINE <<<<<<<<<<<<<<     
                   registry.add(station);
              } catch(Exception e) {
                   System.out.println(e);
    }

    regardless of any other problems in your code, neither of the objects which you are subclassing from UnicastRemoteObject call the superclass constructor, which is a pretty basic flaw - in this case, it will lead to neither of these objects being exported properly.

  • RMI server object getting garbage collected

    Hi all,
    I have seen a number of posts regarding the ConnectException and found that this can occur in a number of situations.
    I am having a problem here.
    I am having an RMI server that is always up and running. And the server object gets requests from the client at regular intervals. But, when the server object is not receiving any requests for a long time (ex: 1 day), then I think the remote object itself is getting garbage collected. And so, tough I am able to get the remote reference using the lookup method, I am getting "Connection refused to host: 192.168.0.216; nested exception is:
         java.net.ConnectException: Connection refused" when I call a method using this reference.
    I believe that this is because the server object getting garbage collected as there are no requests for the server since long. Please correct me if my assumption is wrong.
    I want to know, after how much time the server object gets garbage collected if no requests are received. But, my requirement is that the server object should always be available and WHENEVER a client request comes then that should be processed. What should I do to accomplish this task.
    If any one have any suggestions, please reply as soon as possible.
    Thanks in advance,
    srik4u

    You might do some research into using an activatable remote object. You run rmid (the rmi activation deamon) and register a subclass of java.rmi.activation.Activatable (instead of the usual UnicastRemoteObject) with it. With an activatable object, the remote reference to the activatable object doesn't need to have a live object behind it. If an activatable object is not running (ie: it hasn't been constructed yet, or it has been garbage collected ...as in your case) a remote reference to the object can still be exported to a client. The first time the client calls a method on the remote object, the activation service on the server sees the object is not active, and activates the object for the client. If the object is running ...it is rmi as usual. But if it gets gc'd again, the next invocation on the remote object will trigger the activation service again.
    (The above explanation paraphrases author David Flanagan from Java Enterprise in a Nutshell, O'Reilly)
    I have only built one of these, which loosely followed an example from the above mentioned book. It's a whole other ballgame over and above a regular rmi object. But like anything else, if you dig in and get your head wrapped around it, it eventually makes sense. Ok, why lie ...it confused the hell out of me and left me a little queasy. But you know the drill, by the time you build a few of them it will probably seem as easy as mapping the human genome, right? At any rate, it seems like what you might be after ...so have a look at it. Good luck, and wear your lifejacket.

  • Passing a object from browser to server

    How can i pass a java object from browser to server, can anybody help me in knowing this?
    Rajesh.

    You might need to clarify this. What exactly do you need to do? You can't pass anything from a browser except HTML, other than by attachment. If you have a Java object, then I assume that you are using JSP or something that supports Java, in which case you are already using server-side semantics.
    If however, you mean Javascript, that's a whole other problem, as it is client side only.
    Perhaps if you clarify what you are trying to do someone can give you a good answer.
    Regards,
    Paul

  • RMI Server Object Pooling

    Hello All,
    Does WLServer6.1 take care of having a pool of RMI Server objects, similar
    to the way EJB container does it for EJBs. I guess what I am trying to
    achieve is an effect of Servlets that spawn light threads per invocation
    though now using RMI Server Object. I did look at the "executeThreadPool"
    options which would allow for increasing performance. I am not 100%
    satisfied with it though. Is there any way I can do this. Thanks,
    Chirag

    "Pyung Yoon" <[email protected]> writes:
    MediatorInterface mediator = (MediatorInterface) java.rmi.Naming.lookup("rmi://localhost:7001/TestMediator);This implies JRMP which the server does not support. You need to use t3 or iiop.
    andy

  • Regular RMI server object with WebLogic JNDI

    Is that possible to register a regular RMI object with WebLogic JNDI
    tree? I was building a simple program (using javac and rmic only) based
    on the java.rmi.* (without changing the import statements to
    weblogic.rmi.*) and using the weblogic.jndi to register the server
    object. Below is some piece of code,
    Context ctx = null;
    Hashtable ht = new Hashtable();
    ht.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
    ht.put(Context.PROVIDER_URL, "t3://172.20.20.20:7001");
    ctx = new InitialContext(ht);
    ctx.bind("HelloServer", obj);
    The code failed for the following reason,
    javax.naming.NamingException. Root exception is
    java.rmi.MarshalException: failed to marshal public abstract void
    weblogic.jndi.internal.NamingNode.bind(java.lang.String,java.lang.Object,java.util.Hashtable)
    throws javax.naming.NamingException,java.rmi.RemoteException; nested
    exception is:
    java.rmi.server.ExportException: A description for
    examples.rmi.hello.HelloImpl was found but it could not be read due to:
    [Failed to find examples.rmi.hello.HelloImpl_WLStub or
    examples.rmi.hello.Hello_WLStub for class examples.rmi.hello.HelloImpl]
    java.rmi.StubNotFoundException: Failed to find
    examples.rmi.hello.HelloImpl_WLStub or examples.rmi.hello.Hello_WLStub
    for class examples.rmi.hello.HelloImpl
    at
    weblogic.rmi.internal.BasicDescriptor.<init>(BasicDescriptor.java:101)
    at
    weblogic.rmi.internal.BasicRuntimeDescriptor.<init>(BasicRuntimeDescriptor.java:50)
    at
    weblogic.rmi.internal.DescriptorManager.resolveClass(DescriptorManager.java:55)
    at
    weblogic.rmi.internal.DescriptorManager.getDescriptor(DescriptorManager.java:39)
    at
    weblogic.rmi.internal.DescriptorManager.getDescriptor(DescriptorManager.java:30)
    at
    weblogic.rmi.internal.OIDManager.getRequestDispatcher(OIDManager.java:281)
    at
    weblogic.rmi.internal.OIDManager.getReplacement(OIDManager.java:270)
    at
    weblogic.rmi.internal.OIDManager.replaceObject(OIDManager.java:98)
    at
    weblogic.common.internal.ChunkedObjectOutputStream.replaceObject(ChunkedObjectOutputStream.java:55)
    at
    weblogic.common.internal.ChunkedObjectOutputStream$NestedObjectOutputStream.replaceObject(ChunkedObjectOutputStream.java:239)
    Any idea?
    - SteveC

    "Pyung Yoon" <[email protected]> writes:
    MediatorInterface mediator = (MediatorInterface) java.rmi.Naming.lookup("rmi://localhost:7001/TestMediator);This implies JRMP which the server does not support. You need to use t3 or iiop.
    andy

  • Java.rmi.server.ExportException: object already exported

    I'm encountering an RMI error that I have never seen before. The exception is the following :
    <p><b>
    java.rmi.server.ExportException: object already exported
    </b>
    I am only invoking the UnicastRemoteObject.exportObject() method once. Any ideas on why this error is occurring? This one is about to drive me crazy.
    Thanks in advance!

    There is no need to exportObject() if your implementor extends the UnicastRemoteObject. In such a case it is automatically exported. However in the other case when not extending UnicastRemteObject it can be explicitly exported by exportObject methods.

  • Passing byte[] Tomcat to RMI server

    Hi!
    I have a webapplication powered by Tomcat and RMI used for database access. I get into problem, when someone enters high-ASCII characters to be save in our MS SQL db. I tried doing following:
    byte[] bytes = myString.getBytes( "UTF-8" );
    I pass bytes through rmi server to appropriate class. Within that class
    I recreate string new String( bytes, "UTF-8" ); At this point all high-ASCII replaced with ?. Do you have any suggestions or help on this?
    Thanks

    If you want to encode/decode like that, take a look at the URLEncoder/URLDecoder classes in the java.net package which probably works faster than what you're doing now.
    I have to agree with the other poster, though, that you need to find some way of detecting what character set is used by the different clients. What you're doing now, in effect, is just storing the raw text you get from the client, then presenting it back as it came from the client. This will get you into trouble if you store some text from a Mac user, then present it back to a PC user who may use another character set.
    Any solution to this problem starts by detecting the character set used by the client. Here are five possible ways of doing this in an HTTP environment:
    1. See if the clients send any headers with the POST request -- eg. an "Accept-Charset" header -- that hints at what character set is used. You may use HttpServletRequest.getHeader() for this.
    2. Extract the client platform from the HTTP "User-Agent" header, mapping this to a likely character set.
    3. Check for existence of "tell-tale" characters in the text, again using this to decide the likely character set. An advanced version of this technique will use the frequency distribution of all the 8-bit characters.
    4. Make the client send the character set in use as a hidden parameter. You should be able to use JavaScript to set the hidden parameter.
    5. If your system includes user profiles, make the character set a part of the user profile, settable by the user.

  • How are objects and values passed in rmi?

    how are objects and values passed in rmi?

    In java there are two mwthods of passing aruguments and returning results.
    1) by value
    2) by reference.
    While invoking local methods, java passes primitive types by value and objects by reference.
    However while invoking remote methods both these data types are passed by value. Except for the objects being exported. Reason being two different JVM's are involved and thus memory addresses references of one are meaningles for the other. However "pass by value" for values of type object are implemented as deep copy.

  • Choosing the port of an RMI server

    I need a server working on a port wich is differet from the default 1099, e.g. 2500.
    I create my server object which extends UnicastRemoteObject with code like this
    public MyServer(int port)
    super(port);
    Befor starting the server I run rmiregistry 2500 and the I pass the port number to the server by command line.
    It seems all right to me but I get the same an error message.
    What's wrong?
    Thanks in advance for answers

    I' m sorry. I'm new to RMI and I wrote a Chess Playing RMI software for university. I have managed to make it work on the default port but I don't know how to "escape" from 1099.
    I surfed the Internet for tutorials or code samples but they simply say: "To create an RMI server on the default port 1099 write code like this..." and I can't find the way of changing the port anywhere.
    I didn't write the exact error messaage, and I apologize for that, but it's because I did many trials and often the message changed. It's enough that someone tells me how I have to look to learn the exact way of programming an RMI server on a chosen port.
    Thanks

  • [RMI] server/client, help me.

    I have done a Chat with RMI, between a server and a client machine on my network.
    The server start normaly, and the client manage to connect the server, but the server failed to connect the client.
    Can Someone explain me why?
    Here are the source files:
    *********Client Distant****************
    import java.rmi.*;
    public interface ClientDistant extends java.rmi.Remote {
    public void msg(Message m) throws RemoteException;
    **********Client DistantImplementation**************
    import java.io.*;
    import java.net.*;
    import java.rmi.*;
    import java.rmi.server.*;
    import java.rmi.registry.*;
    import java.net.MalformedURLException;
    public class ClientDistantImpl extends java.rmi.server.UnicastRemoteObject implements ClientDistant, Runnable {
    String nom;
    String nomServeur;
    /** Constructs ClientDistantImpl object and exports it on default port.
    public ClientDistantImpl(String nom, String nomServeur) throws RemoteException {
    super();
    this.nom = nom;
    this.nomServeur= nomServeur;
    Thread leThread = new Thread(this);
    leThread.start();
    /** Register ClientDistantImpl object with the RMI registry.
    * @param name - name identifying the service in the RMI registry
    * @param create - create local registry if necessary
    * @throw RemoteException if cannot be exported or bound to RMI registry
    * @throw MalformedURLException if name cannot be used to construct a valid URL
    * @throw IllegalArgumentException if null passed as name
    public static void registerToRegistry(String name, Remote obj, boolean create) throws RemoteException, MalformedURLException{
    if (name == null) throw new IllegalArgumentException("le nom doit etre non vide");
    try {
    Naming.bind(name, obj);
    } catch (AlreadyBoundException ex){
              throw new IllegalArgumentException("le nom est deja utilise");
    } catch (RemoteException ex){
    if (create) {
    Registry r = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
    r.rebind(name, obj);
    } else throw ex;
    /** Main method.
    public static void main(String[] args) {
    System.setSecurityManager(new RMISecurityManager());
    try {
    BufferedReader entree = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Entrez votre nom");
    String nom = entree.readLine();
    System.out.println("Entrez le nom de la machine serveur");
    String nomServeur = entree.readLine();
    ClientDistantImpl obj = new ClientDistantImpl(nom, nomServeur);
    String machineLocale = InetAddress.getLocalHost().getHostAddress();
                   System.out.println("Machine locale : "+machineLocale);
                   String[] tab = Naming.list("//"+nomServeur);
                   for(int i=0; i<tab.length; i++)
                        System.out.println(tab[i] + " est enregistre sur le registre du serveur");
    ServeurChat sc = (ServeurChat) Naming.lookup("//"+nomServeur+"/serveurChat");
    String url = "//"+machineLocale+"/"+nom;
    sc.connect(url);
    System.out.println("Entrez vos messages en terminant par FIN");
    String mess = entree.readLine();
    while(!mess.equalsIgnoreCase("FIN")) {
    Message m = new Message(url, mess);
    sc.msg(m);
    mess = entree.readLine();
    sc.disconnect(url);
              System.exit(1);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void msg(Message m) throws RemoteException {
    System.out.println(m);
    public void run() {
    try {
    registerToRegistry(nom, this, true);
    } catch (Exception ex) {
    ex.printStackTrace();
              System.exit(1);
    ****************Serveur Chat********************
    import java.rmi.*;
    public interface ServeurChat extends ClientDistant {
    public void connect(String url) throws RemoteException;
    public void disconnect(String url) throws RemoteException;
    *****************Serveur Chat Implementation**********
    import java.net.*;
    import java.util.*;
    import java.rmi.*;
    import java.rmi.server.*;
    import java.rmi.registry.*;
    import java.net.MalformedURLException;
    /** Unicast remote object implementing ServeurChat interface.
    * @author Patrice Torguet
    * @version 1.0
    public class ServeurChatImpl extends UnicastRemoteObject implements ServeurChat {
    Vector clients;
    /** Constructs ServeurChatImpl object and exports it on default port.
    public ServeurChatImpl() throws RemoteException {
    super();
    clients = new Vector();
    public static void registerToRegistry(String name, Remote obj, boolean create) throws RemoteException, MalformedURLException{
    if (name == null) throw new IllegalArgumentException("registration name can not be null");
    try {
    Naming.rebind(name, obj);
    } catch (RemoteException ex){
    if (create) {
    Registry r = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
    r.rebind(name, obj);
    } else throw ex;
    /** Main method.
    public static void main(String[] args) {
    System.setSecurityManager(new RMISecurityManager());
    try {
    String machineLocale = InetAddress.getLocalHost().getHostName();
    System.out.println("Nom du serveur = serveurChat");
    ServeurChatImpl obj = new ServeurChatImpl();
    registerToRegistry("serveurChat", obj, true);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void disconnect(String url) throws RemoteException {
    clients.removeElement(url);
    public void msg(Message m) throws RemoteException {
    Enumeration e = clients.elements();
    String url = null;
    while(e.hasMoreElements()){
    try {
    url = (String) e.nextElement();
    if (!url.equalsIgnoreCase(m.url)) {
    ClientDistant cl = (ClientDistant) Naming.lookup(url);
    cl.msg(m);
    } catch(Exception ex) {
    ex.printStackTrace();
    clients.removeElement(url);
    public void connect(String url) throws RemoteException {
    clients.addElement(url);
    *************Message*********************
    import java.io.*;
    * @author Patrice Torguet
    * @version
    public class Message implements Serializable {
    String url;
    String msg;
    /** Creates new Message */
    public Message(String url, String msg) {
    this.url = url;
    this.msg = msg;
    public String toString() {
    return url + " : " + msg;
    Thx for help.

    This is the exception:
    java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
    java.net.ConnectException: Connection refused
    java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:350)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:137)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:124)
    at java.net.Socket.<init>(Socket.java:268)
    at java.net.Socket.<init>(Socket.java:95)
    at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:20)
    at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:115)
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:494)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:185)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:169)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:78)
    at ServeurChatImpl_Stub.connect(Unknown Source)
    at ClientDistantImpl.main(ClientDistantImpl.java:85)

Maybe you are looking for

  • How to print in black and white

    I am new to Mac, and notice that I cannot do two things: 1. I cannot print selected text by right clicking 2. and , I cannot print anything in Black and white, even though my HP computer is set at black only on the host PC it is connected to. Even if

  • Creation of service notificatioin with reference error

    Hi, will somebody help me to resolve my error encountered when Im creating service notification with reference, having this dialog box appear " SAP office express info " - Express document "Update was terminated". Though the service notification alre

  • Several ranges in a query

    Is it possible to allow the end user to specify several ranges in a query variable? Standard variable types are : single value, several values and range, so I think it could not be done directly. But maybe this problem is common and a good solution a

  • TCP Syslog output for routers and switches

    I am installing a Log Correlation Server at a Customer site whom is very heavy Cisco. I have a 3825 at their Border, ASA boxes on both sides of the DMZ, and 40 + cisco Switches in the Infrastructure routing between Production VLAN's. One of the featu

  • ERM Role Methodology Process - Steps

    Hello Gurus, I am on SP17 and have uploaded relevant init files. Have also performed background job sync. When I create a role in Role Definition stage and save it, the role does not pass or promote to next step i.e. Role Authorization Stage. GRC sav