使用 JavaMail 的 keepConnectionAlive 保持 IMAP IDLE 连接有效
Using JavaMail's keepConnectionAlive to keep an IMAP IDLE connection alive
我一直在努力保持 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 class 有一个 keepConnectionAlive 方法。我想知道是否有人有使用这种方法的经验。它说它将 "Issue a noop command for the connection if the connection has not been used in more than a second."
此方法是否可以很好地替代 Code Review 中的代码?
没有什么能让你们的联系永远保持下去。您的程序需要能够处理连接失败。
通常情况下,服务器会断开 30 分钟未使用的连接。如果您不关心服务器的想法,并且想通过保持未使用的连接打开更长时间来滥用它,您需要做的就是每 29 分钟调用一次 Folder.getMessageCount。 (IMAPFolder.doCommand 的使用不必要地复杂。)如果仍然失败,请重新连接。
我一直在努力保持 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 class 有一个 keepConnectionAlive 方法。我想知道是否有人有使用这种方法的经验。它说它将 "Issue a noop command for the connection if the connection has not been used in more than a second."
此方法是否可以很好地替代 Code Review 中的代码?
没有什么能让你们的联系永远保持下去。您的程序需要能够处理连接失败。
通常情况下,服务器会断开 30 分钟未使用的连接。如果您不关心服务器的想法,并且想通过保持未使用的连接打开更长时间来滥用它,您需要做的就是每 29 分钟调用一次 Folder.getMessageCount。 (IMAPFolder.doCommand 的使用不必要地复杂。)如果仍然失败,请重新连接。