Selector Iterate Example

This program demonstrates iterating over selected keys.

Problem Statement

Write a Java program that iterates over selected keys from Selector and handles events.

Source Code

1 import java.net.*;
2 import java.nio.*;
3 import java.nio.channels.*;
4 import java.util.*;
5 public class SelectorIterateExample {
6 public static void main(String[] args) throws Exception {
7 System.out.println("Eduinq Selector Iterate Example");
8 Selector selector=Selector.open();
9 SocketChannel sc=SocketChannel.open(new InetSocketAddress("localhost",5000));
10 sc.configureBlocking(false);
11 sc.register(selector,SelectionKey.OP_READ);
12 selector.select();
13 Iterator<SelectionKey> it=selector.selectedKeys().iterator();
14 while(it.hasNext()){
15 SelectionKey key=it.next();
16 if(key.isReadable()){ System.out.println("Eduinq Handling Read Event"); }
17 it.remove();
18 }
19 sc.close(); selector.close();
20 }
21 }

Program Output

					Eduinq Selector Iterate Example
Eduinq Handling Read Event
				

Explanation

Uses iterator to process selected keys. - Removes keys after handling. - Exception handling ensures safe operations. - In enterprise systems, iteration supports event driven design. Conclusion: Shows iterating over selected keys.

Quick Links to Explore