简体   繁体   中英

Shutting down a Java RMI server

  1. When I launch the GUI, it starts a new thread.

     final Server myServer = new Server(); final Thread t1 = new Thread(myServer, "T1"); t1.start(); 
  2. The GUI only has a button that will stop the thread upon clicking:

     final JButton btnStartServer = new JButton("Stop server"); btnStartServer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { myServer.stop(); } }); 
  3. The thread will create an object TrackingServiceImpl which is the Java RMI server. Thread itself looks like this:

     class Server implements Runnable { private volatile boolean exit = false; public void run() { try { TrackingService server1 = new TrackingServiceImpl(); TrackingService serverInstance, stub = null; Registry registry = null; while (!exit) { serverInstance = ((TrackingServiceImpl) server1).getInstance(); stub = (TrackingService) UnicastRemoteObject.exportObject((TrackingService) serverInstance, 0); registry = LocateRegistry.createRegistry(4444); registry.bind("TrackingService", stub); System.out.println("Tracking service has started at port " + 4444); } System.out.println("Server is stopping...."); registry.unbind("TrackingService"); UnicastRemoteObject.unexportObject(registry, false); } catch (Exception e) { } } public void stop() { exit = true; } } 
  4. Now if I click on the button before connecting any client to the server, the code works. Clients won't be unable to connect to the server. However, if I let a client connect to the server, and then I click on the button, the client continues to be able to invoke methods on the server even though the server should already have stopped (registry unbinded and exported).

Thanks in advance!

None of this makes sense. Your code does not execute correctly. You don't need the loop or the exit variable, or the Runnable either, or the thread. Once the remote object is constructed, exported, and bound, it is available to clients for remote method calls. To stop it, just unbind it and unexport it with UnicastRemoteObject.unexportObject() . NB At present you're only unexporting the Registry. There's no real need to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM