我正在使用RMI Java在Java中编写一个客户端-服务器对。我希望服务器侦听连接,并且在连接一个客户端时,该服务器应拒绝任何其他尝试连接的客户端。
最佳答案
您将需要使用http://download.oracle.com/javase/6/docs/api/java/rmi/registry/LocateRegistry.html#createRegistry%28int,%20java.rmi.server.RMIClientSocketFactory,%20java.rmi.server.RMIServerSocketFactory%29在代码中启动RMI注册表,并编写一个自定义的RMIServerSocketFactory来返回仅接受单个连接的ServerSocket。
编辑:使用LocateRegistry.createRegistry和http://download.oracle.com/javase/1.5.0/docs/guide/rmi/hello/Server.java的混搭,并添加了一些额外的代码(请注意,我没有进行编译,因此您需要自己整理所有编译错误;它旨在向您展示常规用法):
编辑2:修复它以合并@EJP的建议(有关更多详细信息,请参见this)。
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello {
public Server() {}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
RMIClientSocketFactory csf = new RMIClientSocketFactory() {
@Override
public Socket createSocket(String host, int port) throws IOException {
InetAddress addr = InetAddress.getByName(host);
if (addr.equals(InetAddress.getLocalHost())) {
return new Socket(addr, port);
} else {
throw new IOException("remote socket bind forbidden.");
}
}
};
RMIServerSocketFactory ssf = new RMIServerSocketFactory() {
@Override
public ServerSocket createServerSocket(int port) throws IOException {
System.out.println("RMIServerSocketFactory().createServerSocket()");
return new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
}
};
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0, csf, ssf);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.createRegistry(uri.getPort(), csf, ssf);
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
关于java - 如何创建一次只能接受一个连接的RMI服务器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6393504/