我对RMI技术完全陌生,但我认为它是构建真实世界分布式应用程序的一个非常重要的中间件架构。我在尝试将客户端程序连接到服务器程序时遇到的挑战将我带到了这个站点。我之前做的代码一直给我java.rmi.ConnectException ...无法托管127.0.0.1。实际上我打算先在本地运行这些程序。所以所有程序都在同一台计算机和文件夹中。我的Os是Windows 7.
我遵循了从其他论坛获得的指令/建议,但错误仍然存在。我遵循的指令包括 1在运行服务器程序时引用rmi.server.hostname属性
2编辑\ etc文件夹
下的hosts文件夹同样的例外情况仍然存在。 RMI程序是通过从客户端调用的sayHello()方法打印的基本“Hello world”。现在有人发布了下面显示的代码给我。我尝试从客户端程序连接传递主机名,端口号和字符串文本作为运行时参数,这次持久的异常是java.rmi.UnknownHostException ..我认真想要解决所有这些问题来尝试更大的项目。我很感激如果有人能够提供一切线索。
Olakunle Oladipo Oni
import java.rmi.*;
public interface ReceiveMessageInterface extends Remote
{
void receiveMessage(String x) throws RemoteException;
}
RmiServer.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
public class RmiServer extends java.rmi.server.UnicastRemoteObject
implements ReceiveMessageInterface
{
int thisPort;
String thisAddress;
Registry registry; // rmi registry for lookup the remote objects.
// This method is called from the remote client by the RMI.
// This is the implementation of the �gReceiveMessageInterface�h.
public void receiveMessage(String x) throws RemoteException
{
System.out.println(x);
}
public RmiServer() throws RemoteException
{
try
{
// get the address of this host.
thisAddress= (InetAddress.getLocalHost()).toString();
}
catch(Exception e)
{
throw new RemoteException("can't get inet address.");
}
thisPort=1099; // this port(registry�fs port)
System.out.println("this address="+thisAddress+",port="+thisPort);
try
{
// create the registry and bind the name and object.
registry = LocateRegistry.createRegistry( thisPort );
registry.rebind("rmiServer", this);
}
catch(RemoteException e)
{
throw e;
}
}
static public void main(String args[])
{
try
{
RmiServer s=new RmiServer();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
RmiClient.java
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class RmiClient
{
static public void main(String args[])
{
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
String text=args[2];
System.out.println("sending "+text+" to "+serverAddress+":"+serverPort);
try
{
// get the �gregistry�h
registry=LocateRegistry.getRegistry(serverAddress,
(new Integer(serverPort)).intValue()
);
// look up the remote object
jrmiServer=
(ReceiveMessageInterface)(registry.lookup("rmiServer"));
// call the remote method
rmiServer.receiveMessage(text);
}
catch(RemoteException e){
e.printStackTrace();
}
catch(NotBoundException e){
e.printStackTrace();
}
}
}