java-如何安全关闭rmi客户端?

我想使用RMI协议关闭客户端和服务器之间的所有连接.

   Remote r=  Naming.lookup("rmi://192.168.105.38:9121/AccountRMIService");
   if(r instanceof RmiInvocationWrapper_Stub) {
       RmiInvocationWrapper_Stub stub = (RmiInvocationWrapper_Stub)r;
       System.out.println("hashCode="+stub.getRef().hashCode());
   }
   System.out.println(r);
   //How to close the connection with 'Remote' ?

一些代码来检查服务器的rmi状态:

final ThreadLocal<List<Socket>> currentSocket = new ThreadLocal<List<Socket>>() {

    protected List<Socket> initialValue() {
        return new ArrayList<Socket>();
    }
};
RMISocketFactory.setSocketFactory(new RMISocketFactory() {

    public Socket createSocket(String host, int port) throws IOException {
        Socket socket = new Socket(host, port);
        socket.setKeepAlive(true);
        socket.setSoTimeout(300);
        currentSocket.get().add(socket);
        return socket;
    }

    public ServerSocket createServerSocket(int port) throws IOException {
        return new ServerSocket(port);
    }
});
Remote r = Naming.lookup("rmi://192.168.105.38:9121/AccountRMIService");
if (r instanceof RmiInvocationWrapper_Stub) {
    RmiInvocationWrapper_Stub stub = (RmiInvocationWrapper_Stub) r;
    System.out.println("hashCode=" + stub.getRef().hashCode());
}
Iterator<Socket> s = currentSocket.get().iterator();
while(s.hasNext()) {
    s.next().close();
    s.remove();
}

这不是rmi通讯的客户端.我只想使用RMI协议而不是简单的套接字来检查服务器状态.
有时,服务器仍在运行,但是所有请求都被阻止.

解决方法:

您无法“关闭所有连接”,因为您对基础TCP机制的可见性为零.您可以在客户端中做的最好的事情就是允许所有RMI存根都被垃圾回收.无论如何,基础连接都被集中起来并主动关闭.

上一篇:Java的分布式计算.最好的方法?


下一篇:春季-RMI服务导出程序和HttpInvoker之间的区别?