[英]Java NIO packet sticking
我有一台帶有選擇器的NIO實現的服務器。 實現非常簡單:
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
if (! key.isValid()) {
continue;
}
UserConnection connection = users.get(key);
if (key.isReadable()) {
processReadableKey(key, connection);
} else if (key.isWritable()) {
processWritableKey(key, connection);
}
問題是,當兩個數據包(消息)幾乎立即一個接一個地到達時,選擇器做出反應並處理第一個,但隨后它不做出反應並將相應的密鑰標記為“可讀”以處理第二個。 當下一條消息到達時,選擇器對其進行處理,然后處理“丟失”的數據包。 我不知道如何解決它。 我試圖減少通道緩沖區,並試圖通過selector.wakeup()
喚醒選擇selector.wakeup()
,但這沒有幫助,因為問題在於在處理一對消息中的第一條消息后立即將鍵識別為“可讀”。 有任何想法嗎?
聽起來您需要在使用所選鍵集之前將其刪除。 如果不這樣做,則在調用selectedKeys()
,返回的集合仍將包含舊的,已使用的鍵。
類似於以下內容:
Iterator iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove(); // remove here
process(key);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.