Reputation: 563
I'm trying to find the most elegant way of pairing two socket channels using java NIO. So far I am writing to one channel, reading from it and and writing the result to another. The way I'm going about it seems like a hack and I was wondering if anyone knew of a better way?
public void readyChannels() {
while (true) {
try {
selector.select();// block here until a new IO event
Iterator keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = (SelectionKey) keys.next();
keys.remove();// do not process this again
write(key.channel(),"random data".getBytes());
byte[] bytes = read(key.channel());
write(otherChannel, bytes);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 57
Reputation: 311028
Just make one channel the key-attachment of the other channel's selection key, or better still make an object that contains them both and set that as the attachment.
Upvotes: 1