【1】添加启动参数。-Djava.rmi.server.hostname = 127.0.0.1
这个方法并不会使监听生效,
java.rmi.server.hostname:
Hostname string; default value is the local host's IP address in "dotted-quad" format ... which is embedded into remote stubs created by this JVM when remote objects are exported. This can be used to control the effective IP address of RMI servers exported by multi-homed hosts. This property is read exactly once in the life of the JVM.
【2】关键是:RMIServerSocketFactory
使用自定义的该实现就可以指定绑定的地址。
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
public class RmiServer {
public static void main(String[] args) throws RemoteException, InterruptedException {
RMIServerSocketFactory ssf = new RMIServerSocketFactory() {
@Override
public ServerSocket createServerSocket(int port) throws IOException {
// TODO Auto-generated method stub
return new ServerSocket(port, 0, InetAddress.getByName("127.0.0.1"));
}
};
RMIClientSocketFactory csf = new RMIClientSocketFactory() {
@Override
public Socket createSocket(String host, int port) throws IOException {
// TODO Auto-generated method stub
return new Socket(host, port);
}
};
LocateRegistry.createRegistry(8090, csf, ssf);
System.out.println("Server start....");
Thread.sleep(1000*60);
}
}
参考:
该方法必须覆盖hashCode 和equals 方法,否则会一个消息一个线程 socket 无法重用。