我认为如果您删除
registryHost
属性,它将在 1099 上动态创建一个主机,因为还没有一个主机。
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName" value="spitterService"/>
<property name="service" ref="spitterService"/>
<property name="serviceInterface" value="com.spitter.service.SpitterService"/>
<property name="registryPort" value="1099"/>
</bean>
要么在 1099 上启动 RmiRegistry。
您必须创建
myRmiExporter
并扩展 RMIServiceExporter
然后用这个body来实现这个方法
protected Registry getRegistry(String registryHost, int registryPort,
RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory)
throws RemoteException
{
if (registryHost != null)
{
// Host explictly specified: only lookup possible.
if (logger.isInfoEnabled())
{
logger.info("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]");
}
try
{
Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
testRegistry(reg);
return reg;
}
catch (RemoteException ex)
{
logger.debug("RMI registry access threw exception", ex);
logger.warn("Could not detect RMI registry - creating new one");
// Assume no registry found -> create new one.
LocateRegistry.createRegistry(registryPort);
Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
testRegistry(reg);
return reg;
}
}
else
{
return getRegistry(registryPort, clientSocketFactory, serverSocketFactory);
}
}
成功了
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Random;
public class GuessingGameServer extends UnicastRemoteObject implements GuessingGameInterface {
private int num;
public GuessingGameServer() throws RemoteException {
super();
num = new Random().nextInt(100) + 1;
System.out.println("[Server] Generated number to guess: " + num);
}
public String guessNumber(int guess) throws RemoteException {
System.out.println("[Server] Client guessed: " + guess);
if (guess == num) {
return "Correct!";
} else if (guess < num) {
return "Too Low!";
} else {
return "Too High!";
}
}
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099);
System.out.println("[Server] RMI Registry started on port 1099");
GuessingGameServer game = new GuessingGameServer();
Naming.rebind("rmi://localhost/GuessingGameService", game);
System.out.println("[Server] Guessing Game Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}