IMAP闲置如何工作?

时间:2011-01-06 04:22:22

标签: ruby heroku imap eventmachine

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

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

2 个答案:

答案 0 :(得分:7)

在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

答案 1 :(得分:1)

IMAP IDLE是邮件服务器实现可以支持的功能,允许实时通知。 [Wikipedia]

  

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

     

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

     

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

[RFC 2177 - IMAP4 IDLE command]