我对 RMI 技术完全陌生,但我开始将它视为构建现实世界分布式应用程序的非常重要的中间件架构。我在尝试将客户端程序连接到服务器程序时遇到的挑战将我带到了这个站点。我之前做的代码一直给我 java.rmi.ConnectException...无法托管 127.0.0.1。其实我打算先在本地运行这些程序。所以所有程序都在同一台计算机和文件夹上。我的操作系统是 Windows 7。
我遵循了从其他论坛获得的指令/建议,但错误仍然存在。我遵循的指令包括 1 在运行服务器程序时引用 rmi.server.hostname 属性
2 编辑\etc文件夹下的hosts文件夹
同样的异常仍然存在。RMI 程序是一个基本的“Hello world”,通过从客户端调用的 sayHello() 方法打印出来。现在有人向我发布了下面显示的代码。我尝试从传递主机名、端口号和字符串文本作为运行时参数的客户端程序进行连接,这次持续存在的异常是 java.rmi.UnknownHostException ..我非常想解决所有这些问题以尝试更大的项目。我很感激如果有人可以提供这一切的线索。
奥拉昆勒奥拉迪波奥尼
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();
}
}
}