How can I create different selectors to accept a new connection in java NIO
I want to write java tcp socket programming using java NIO. His work is wonderful. But I am using the same selector to accept read and write to clients.
How to create different selectors to accept new connection in Java NIO, read and write. Is there an online help.
Actually, when I'm busy reading or writing, the selector uses more iterator. Therefore, if more clients are connected, the adoption performance becomes slow. But I don't want the receiving clients to be slow.
// Create a selector and register two socket channels Selector selector = null; try {// Create a selector selector = Selector.open ();
// Create two non-blocking sockets. This method is implemented in
// e173 Creating a Non-Blocking Socket.
SocketChannel sChannel1 = createSocketChannel("hostname.com", 80);
SocketChannel sChannel2 = createSocketChannel("hostname.com", 80);
// Register the channel with selector, listening for all events
sChannel1.register(selector, sChannel1.validOps());
sChannel2.register(selector, sChannel1.validOps());
} catch (IOException e) {
}
// Wait for events
while (true) {
try {
// Wait for an event
selector.select();
} catch (IOException e) {
// Handle error with selector
break;
}
// Get list of selection keys with pending events
Iterator it = selector.selectedKeys().iterator();
// Process each key at a time
while (it.hasNext()) {
// Get the selection key
SelectionKey selKey = (SelectionKey)it.next();
// Remove it from the list to indicate that it is being processed
it.remove();
try {
processSelectionKey(selKey);
} catch (IOException e) {
// Handle error with channel and unregister
selKey.cancel();
}
}
}
public void processSelectionKey(SelectionKey selKey) throws IOException {
// Since the ready operations are cumulative,
// need to check readiness for each operation
if (selKey.isValid() && selKey.isConnectable()) {
// Get channel with connection request
SocketChannel sChannel = (SocketChannel)selKey.channel();
boolean success = sChannel.finishConnect();
if (!success) {
// An error occurred; handle it
// Unregister the channel with this selector
selKey.cancel();
}
}
if (selKey.isValid() && selKey.isReadable()) {
// Get channel with bytes to read
SocketChannel sChannel = (SocketChannel)selKey.channel();
// See e174 Reading from a SocketChannel
}
if (selKey.isValid() && selKey.isWritable()) {
// Get channel that ready for more bytes
SocketChannel sChannel = (SocketChannel)selKey.channel();
}
}
Thanks Deepak
There is a lot of online help available .
If you want to create a new selector, go ahead and create another one (just as you did in the copied sample code). You can register channels with it just for a connect operation if you like (docs close this, but OP_ACCEPT operation). You probably want the thread pool to handle the client processing work - this way your main thread can queue work items and immediately accept new connections into the listening socket.
a source to share