IMAP闲置如何工作?

有人可以向我解释IMAP IDLE的工作原理吗? 它为每个打开的连接分配一个新进程吗? 我可以以某种方式使用eventmachine吗?

我正在尝试使用后台工作者在heroku上的ruby中实现它。 有什么想法吗?

在Ruby 2.0及更高版本中,有一个空闲方法接受一个代码块,每次获得无标记响应时都会调用该代码块。 一旦得到这个响应,你需要突破并拉出进来的电子邮件。空闲调用也是阻塞的,所以你需要在一个线程中执行此操作,如果你想保持它是异步的。

这是一个示例(在这种情况下,@ mailbox是Net :: IMAP的一个实例):

def start_listener() @idler_thread = Thread.new do # Run this forever. You can kill the thread when you're done. IMAP lib will send the # DONE for you if it detects this thread terminating loop do begin @mailbox.select("INBOX") @mailbox.idle do |resp| # You'll get all the things from the server. For new emails you're only # interested in EXISTS ones if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS" # Got something. Send DONE. This breaks you out of the blocking call @mailbox.idle_done end end # We're out, which means there are some emails ready for us. # Go do a seach for UNSEEN and fetch them. process_emails() rescue Net::IMAP::Error => imap_err # Socket probably timed out rescue Exception => gen_err puts "Something went terribly wrong: #{e.messsage}" end end end end 

IMAP IDLE是邮件服务器实现可以支持的function,允许实时通知。 [ 维基百科 ]

IDLE命令可以与任何IMAP4服务器实现一起使用,该实现返回“IDLE”作为CAPABILITY命令支持的function之一。

当客户端准备好接受未经请求的邮箱更新消息时,IDLE命令将从客户端发送到服务器。 服务器使用continuation(“+”)响应请求对IDLE命令的响应。 IDLE命令保持活动状态,直到客户端响应继续,并且只要IDLE命令处于活动状态,服务器现在可以随时自由发送未标记的EXISTS,EXPUNGE和其他消息。

通过从客户端接收“完成”继续来终止IDLE命令; 这样的响应满足服务器的延续请求。 […]客户端在服务器等待DONE时不得发送命令,因为服务器将无法区分命令和延续。

[ RFC 2177 – IMAP4 IDLE命令 ]