Java RMI 超时(崩溃)
我正在使用 RMI 用 Java 编写服务器/客户端程序。当服务器崩溃时,这不是问题,客户端会收到 RemoteException 并断开连接。
但是,当客户端崩溃时我会遇到问题。我的服务器使用计时器时不时地对所有客户端对象执行 ping 操作,当它没有连接到客户端时,它将捕获 RemoteException。
然后,它应该从服务器中删除客户端对象(只需从列表中删除它),但这是不可能的,因为当我尝试对代理客户端对象执行任何操作时,它会抛出另一个 RemoteException。我该如何解决这个问题?
List<User> users;
Map<User, IClient> clients;
class PingClients extends TimerTask {
public void run() {
for (IClient client : clients.values())
try {
client.ping();
} catch (RemoteException e) {
//removeClient(client); GENERATES REMOTEEXCEPTION
}
}
}
public boolean removeClient(IClient c) throws RemoteException{
User u = c.getUser();
users.remove(u);
clients.remove(u);
for (IClient client : clients.values())
client.updateUsers(users);
}
I'm doing a server/client program in Java using RMI. When server crashes it's not a problem, clients get a RemoteException and disconnects.
However I have problems when clients crashes. My server uses a Timer to ping all client objects every now and then, when it gets no connection to a client it will catch a RemoteException.
Then, it's supposed to remove the client object from the server (just by removing it from a list), but it's impossible because when I try to do anything with the proxy client object it will throw another RemoteException. How can I solve this problem?
List<User> users;
Map<User, IClient> clients;
class PingClients extends TimerTask {
public void run() {
for (IClient client : clients.values())
try {
client.ping();
} catch (RemoteException e) {
//removeClient(client); GENERATES REMOTEEXCEPTION
}
}
}
public boolean removeClient(IClient c) throws RemoteException{
User u = c.getUser();
users.remove(u);
clients.remove(u);
for (IClient client : clients.values())
client.updateUsers(users);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您会收到 RemoteException,因为当您尝试删除客户端(已断开连接)时,您首先调用客户端上的 getUser() 方法,这显然会引发 RemoteException。
您应该将代码更改为如下所示:
确保一次只有一个线程可以访问地图。
You get a RemoteException because when you try to remove the client (which is disconnected), you first call the getUser() method on the client, which obviously throws a RemoteException.
You should change your code to something like this :
Make sure that only one thread has access to the map at a time.
第一行,您应该使用 ConcurrentMap 而不是地图。这将为您避免由于并发访问地图而带来的很多麻烦。
First line, you should use ConcurrentMap instead of a Map. This will avoid you a lot of troubles due to concurrent access to your map.
如果
IClient c
是您的远程对象,那么在客户端不可用时对其调用getUser()
显然会引发异常。If
IClient c
is your remote object, callinggetUser()
on it will obviously throw an exception if the client is unavailable..