我一直在努力保持IMAP IDLE连接活着。我的代码与this Code Review非常相似,在大多数情况下都有效,但有时会停止接收消息。
它看起来像这样:
//... some code
ScheduledExecutorService keepAlive = Executors.newScheduledThreadPool(1);
Runnable toKeepAlive = new Runnable() {
public void run() {
keepAliveRunner();
}
};
keepAlive.scheduleAtFixedRate(toKeepAlive,
KEEP_ALIVE_FREQ,
KEEP_ALIVE_FREQ,
TimeUnit.MILLISECONDS);
//... other code ;)
}
public void keepAliveRunner() {
try {
imapFolder.doCommand(new IMAPFolder.ProtocolCommand() {
public Object doCommand(IMAPProtocol p)
throws ProtocolException {
p.simpleCommand("NOOP", null);
return null;
}
});
} catch (MessagingException e) {
e.printStackTrace();
}
}
我看到JavaMail的IMAPFolder类有一个keepConnectionAlive方法。我想知道是否有人有使用这种方法的经验。它表示如果超过一秒钟没有使用连接,它将发出连接的noop命令。"
这种方法是否可以替代Code Review中的代码?
答案 0 :(得分:0)
没有什么能够让你的联系永远存在。您的程序需要能够处理连接失败。
通常,服务器会丢弃30分钟未使用的连接。如果您不关心服务器的想法,并且想要通过保持未使用的连接打开更长时间来滥用它,那么您需要做的就是每29分钟调用一次Folder.getMessageCount。 (IMAPFolder.doCommand的使用不必要地复杂。)如果仍然失败,请重新连接。