Selector Select Example
This program demonstrates selecting ready channels using Selector.
Problem Statement
Write a Java program that waits for channels ready for I/O using Selector.select().
Source Code
| 1 | import java.net.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | import java.util.*; |
| 5 | public class SelectorSelectExample { |
| 6 | public static void main(String[] args) throws Exception { |
| 7 | System.out.println("Eduinq Selector Select 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 | Set<SelectionKey> keys=selector.selectedKeys(); |
| 14 | for(SelectionKey key:keys){ |
| 15 | if(key.isReadable()){ System.out.println("Eduinq Channel Ready for Read"); } |
| 16 | } |
| 17 | sc.close(); selector.close(); |
| 18 | } |
| 19 | } |
Program Output
Eduinq Selector Select Example Eduinq Channel Ready for Read
Explanation
Uses selector.select() to block until channel ready. - Iterates through selected keys. - Exception handling ensures safe operations. - In enterprise systems, Selector.select supports multiplexed I/O. Conclusion: Shows selecting ready channels.