使用Java RMI建立连接

时间:2012-10-18 19:35:07

标签: java rmi

我正在编写一个程序,使用RMI将客户端计算机连接到服务器,到目前为止,我一直在获取java.net.ConnectException: Connection refused

这是我的代码;

接口

public interface ServerInterface extends Remote
{
public String getMessage() throws RemoteException;

}

服务器

public class Server extends UnicastRemoteObject implements ServerInterface 
{
int portNumber = 7776;
String ipAddress;
Registry registry;

public Server() throws RemoteException
{
    try
    {
        ipAddress = "192.168.0.104";
        System.out.println("IP Address: " + ipAddress + " Port Number: " + portNumber);
        registry = LocateRegistry.getRegistry();
        registry.rebind("ServerFour", this);
    }
    catch (RemoteException e)
    {
        System.out.println("Remote Exception Error");
    }
}

public String getMessage() throws RemoteException
{
    String output = "Connected to Server";

    return output;
}

public static void main(String args[])
{
    try
    {
        Server server = new Server();

    }
    catch (RemoteException ex)
    {
        System.out.println("Remote Exception in Main");
    }

}

}

客户端

public class Client 
{
public static void main(String[] args) throws NumberFormatException, RemoteException, NotBoundException 
{
    try
    {
        ServerInterface server;
        Registry registry;

        String serverAddress = "192.168.0.104";
        String serverPort = "7776";

        registry = LocateRegistry.getRegistry(serverAddress, Integer.valueOf(serverPort));

        server = (ServerInterface)(registry.lookup("ServerFour"));

        String serverMessage = server.getMessage();

    System.out.println("Servers Message: " + serverMessage);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }


}


}

现在我只希望客户端调用ServerInterface中的方法并打印出它的消息,但我似乎无法让它工作。当我启动客户端时,我收到上面显示的异常消息。

当我启动服务器时,它返回:

IP地址:client4 / 127.0.1.1端口号:1234

更新

我已将端口号更改为7776 Ran rmiregistry 7776&

这是我启动Server并运行netstat -anpt时得到的结果 http://i.imgur.com/GXnnG.png

现在在客户端,我得到了这个: http://i.imgur.com/aBvW3.png

1 个答案:

答案 0 :(得分:0)

似乎RMI Registry绑定到localhost(参见127.0.0.1 - 我假设127.0.1.1是拼写错误?),但尝试通过{{{ 1}} - 这是行不通的,因为没有什么可能是在监听那个界面!请尝试将客户端192.168.0.104更改为serverAddress

命令127.0.0.1(或在Windows上:netstat -anpt)是您的朋友,当您想要查看哪些进程绑定在哪些接口上时(netstat -anbt依旧为TCP)

这是将注册表绑定到特定IP(例如t),

的方法
localhost

干杯,