我正在编写一个使用 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 &
这是我启动服务器并运行 netstat -anpt http://i.imgur.com/GXnnG.png时得到的
现在在客户端我得到这个:http: //i.imgur.com/aBvW3.png