2011-01-06 76 views
4

有人可以向我解釋IMAP IDLE的工作原理嗎?它爲每個打開的連接分配一個新的進程嗎?我可以以某種方式使用eventmachine嗎?IMAP閒置如何工作?

我正試圖在heroku上與後臺工作人員一起實現它。有什麼想法嗎?

+0

你想知道IMAP IDLE是什麼,你需要什麼樣的數據發送回客戶端時,還是您想知道如何在現有的IMAP服務器中實現IMAP IDLE? – dkarp 2011-01-06 13:53:33

+0

IMAP IDLE是IMAP協議的一部分。所以,是的,dkarp問道:你想知道協議規範是什麼,或者如何在網站上實現它(我猜你不是在製作IMAP服務器,因爲你在談論heroku)。 – henrikhodne 2011-01-26 05:42:03

+0

請參閱此處以獲取答案:http://stackoverflow.com/a/1818718/459863 – 2012-12-21 00:12:22

回答

0

IMAP IDLE是郵件服務器實現可支持的功能,允許實時通知。 [Wikipedia]

IDLE命令可以與任何IMAP4服務器實現一起使用,該實現將「IDLE」作爲CAPABILITY命令支持的功能之一返回。

當客戶機準備好接收未經請求的郵箱更新消息時,IDLE命令從客戶機發送到服務器。服務器使用continuation(「+」)響應請求對IDLE命令的響應。在客戶端響應延續之前,IDLE命令保持活動狀態,只要IDLE命令處於活動狀態,服務器現在可以隨時發送未標記的EXISTS,EXPUNGE和其他消息。

IDLE命令終止於客戶端收到「完成」延續;這樣的響應滿足服務器的繼續請求。 [...]當服務器等待DONE時,客戶端不能發送命令,因爲服務器將無法區分命令和延續。

[RFC 2177 - IMAP4 IDLE command]

6

在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 
+0

謝謝!最後你的例子清除了我的想法。我在這裏寫了一個完整的腳本:https://gist.github.com/solyaris/b993283667f15effa579 – 2014-12-13 16:20:32