Selector Register Example
This program demonstrates registering a channel with Selector.
Problem Statement
Write a Java program that registers a SocketChannel with Selector for OP_READ.
Source Code
| 1 | import java.net.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | public class SelectorRegisterExample { |
| 5 | public static void main(String[] args) throws Exception { |
| 6 | System.out.println("Eduinq Selector Register Example"); |
| 7 | Selector selector=Selector.open(); |
| 8 | SocketChannel sc=SocketChannel.open(new InetSocketAddress("localhost",5000)); |
| 9 | sc.configureBlocking(false); |
| 10 | sc.register(selector,SelectionKey.OP_READ); |
| 11 | System.out.println("Eduinq Channel Registered with Selector"); |
| 12 | sc.close(); selector.close(); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Selector Register Example Eduinq Channel Registered with Selector
Explanation
Uses Selector.open() for multiplexing. - Registers channel for read operations. - Exception handling ensures safe operations. - In enterprise systems, Selector supports scalable networking. Conclusion: Shows registering with Selector.