当前位置:编程学习 > JAVA >>

java rmi怎样实现服务器间的通信

局域网中有一若干台主机,每台服务器上存有大量资源。其中一台为主服务器,其余为从服务器,主服务器先开启,其余从服务器开启后分别向主服务器发送自己的IP,表明自己开启(为后来的的资源搜索做准备)。主服务器把收到的IP汇总,放到一个文件里,分别发送的各个从服务器。
语言为java ,各位高手请问怎么实现
答案:有几个建议
1:主服务器不用主动发IP给子服务器(主服务器不可能知道子服务器的数目),也没有必要主服务来发,完全可以让子服务器来主动向主服务索取IP。
2:结果完全没有必要以文件形式存放(每次开机要重新获得,没有必要做持久化),完全可以存到一个Set中。

根据以上:我做一个简单的实现:
***********************************************
IHost.java

package test.rmi.host;

import java.rmi.RemoteException;
/**
* remote interface
*
*/
public interface IHost extends java.rmi.Remote
{
void register(String ip) throws RemoteException;

String[] getAllSubServerList() throws RemoteException;

}
***********************************************
Host.java

package test.rmi.host.impl;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashSet;
import java.util.Set;

import test.rmi.host.IHost;

/**
*
* the implentation class of Ihost
*
*/
public class Host extends UnicastRemoteObject implements IHost
{
private static final long serialVersionUID = -2197983171132594422L;

private Set<String> subServers = new HashSet<String>();

public Host() throws RemoteException
{

super();
}

public String[] getAllSubServerList() throws RemoteException
{

String[] ips = new String[] {};

synchronized (this)

{

ips = subServers.toArray(ips);

}
return ips;
}

public void register(String ip) throws RemoteException
{

synchronized (this)

{

subServers.add(ip);

}
}
}
***********************************************
ServiceStartup.java

package test.rmi.host;

import java.rmi.Naming;

import test.rmi.host.impl.Host;

/**
* The main class for Host server,mainly for start up the host
*
*/
public class ServiceStartup
{
public static void main(String args[]) throws Exception
{

Host host = new Host();

Naming.rebind("HostServer", host);
}

}
***********************************************
SubServerStartup.java

package test.rmi.sub;

import java.net.InetAddress;
import java.rmi.Naming;

import test.rmi.host.IHost;

/**
* The main class for Sub server,mainly for start up the sub
*
*/
public class SubServerStartup
{
public static void main(String args[]) throws Exception
{

String hostIp = "";

IHost host = (IHost) Naming.lookup("rmi://" + hostIp + "/HostServer");

String myIp = InetAddress.getLocalHost().toString();

host.register(myIp);


//do something...

try{

//wait for other sub server start up

Thread.sleep(3000);

}catch(Exception e){}


String[] allSubServer = host.getAllSubServerList();

//do something...
}
}
***********************************************

本实现只是提供一个简单的思路和基本的技术实现,希望可以帮助到你
以上代码已经可以运行了,你说的具体点,是哪方面?是如何运行rmi程序吗?

上一个:JAVA多线程程序设计,有追加200分
下一个:java读取配置文件的方法(xml)

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,