RMI 监听本地端口

如何让RMI端口真正只监听本地端口?127.0.0.1

【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);
		
	}
}

RMI 监听本地端口_第1张图片


参考:

http://stackoverflow.com/questions/10173834/java-rmi-djava-rmi-server-hostname-localhost-still-opens-a-socket-listening-on



该方法必须覆盖hashCode 和equals 方法,否则会一个消息一个线程 socket 无法重用。

你可能感兴趣的:(java,localhost,rmi,127.0.0.1)