gpt4 book ai didi

java - 停止 RMI 服务器的干净方法

转载 作者:行者123 更新时间:2023-11-30 11:21:10 25 4
gpt4 key购买 nike

没有 stopServer 功能也能正常工作的 RMI 服务器。

public class HelloServer extends UnicastRemoteObject implements HelloInterface
{
private final static int PORT=1102;
private final String serverName="server";
private Timer timer;

public HelloServer() throws RemoteException
{
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new StopServerTask(), 5000);

}

@Override
public String serverResponse(String request) throws RemoteException
{
return "Hello"+request;
}


public static void main(String[] args)
{

try
{

HelloServer skeleton=new HelloServer();
System.out.println("Starting server");
skeleton.startServer();
System.out.println("Server started");


}
catch (RemoteException ex)
{
ex.printStackTrace();
}


}

public void startServer()
{
try {

HelloServer skeleton=new HelloServer();
Registry reg=LocateRegistry.createRegistry(PORT);
reg.rebind(serverName, skeleton);
System.out.println("Server is ready");

} catch (RemoteException ex)
{
Logger.getLogger(HelloInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}

public void stopServer()
{
System.out.println("Stopping server");
try {

Registry rmiRegistry = LocateRegistry.getRegistry(PORT);
HelloInterface myService = (HelloInterface) rmiRegistry.lookup(serverName);

rmiRegistry.unbind(serverName);

UnicastRemoteObject.unexportObject(rmiRegistry, true);

} catch (NoSuchObjectException e)
{
e.printStackTrace();
} catch (NotBoundException e)
{
e.printStackTrace();
} catch (RemoteException ex) {
Logger.getLogger(HelloServer.class.getName()).log(Level.SEVERE, null, ex);
}
}

class StopServerTask extends TimerTask
{

@Override
public void run()
{
stopServer();
}

}
}

每当调用异常中的 stopServer() 被抛出时

UnicastRemoteObject.unexportObject(rmiRegistry, true);

这是堆栈轨迹

java.rmi.NoSuchObjectException: object not exported
at sun.rmi.transport.ObjectTable.unexportObject(ObjectTable.java:153)
at java.rmi.server.UnicastRemoteObject.unexportObject(UnicastRemoteObject.java:297)
at rmi.HelloServer.stopServer(HelloServer.java:84)

即使我使用清理服务对象,情况也是一样

 UnicastRemoteObject.unexportObject(myService, true);

有人可以建议一个干净的方法来停止服务器,同时释放端口以供重用。

最佳答案

您需要存储 LocateRegistry.createRegistry(), 的结果并取消导出它。目前您正在尝试取消导出 stub 。

关于java - 停止 RMI 服务器的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22371487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com