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



参考:

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



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

转载于:https://www.cnblogs.com/scugxl/p/4131783.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值