harryos said:
i am learning java.nio from ibm alphawks tutorial that has a
Multiportecho application .I tested it using ordinary io socket client
that reads keyboard input and sends to server .But i am unable to
figure out how to do the same using nio classes.Can anybody give me a
nio client app so i can learn how it works?
Using NIO from a client is not much different than from a server. The
steps are more or less as follows:
(1) You'll basically have two threads: one reading your keyboard input
and another handling the NIO stuff (the selector loop);
(2) Create some object that will wrap around the data that is waiting
to be sent down the socket at any given time;
(3) Connect using a socket channel:
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
InetSocketAddress socketAddress =
new InetSocketAddress(hostAddr, port);
// this next object is what your keyboard thread will
// post pending output to
DataWrapper d = new DataWrapper();
sc.register(selector, SelectionKey.OP_CONNECT, d);
sc.connect(socketAddress);
(4) Your selector thread looks something like this:
while (!stopRequest) {
if (selector.select() == 0) continue;
for (Iterator it = selector.selectedKeys().iterator();
it.hasNext()

{
SelectionKey key = (SelectionKey) it.next();
it.remove();
if (!key.isValid()) continue;
DataWrapper data = (DataWrapper) key.attachment();
SocketChannel sc = (SocketChannel) key.channel();
try {
if (key.isConnectable()) {
if (!sc.finishConnect()) {
// close sc and signal problem to kb thread
} else {
// signal to kb thread that it can send data
}
}
if (key.isWritable()) {
synchronized (data) {
// send data from 'data' down the
// sc socket channel; if all data in the buffer is now
// sent, de-register for writes
}
}
} catch (Exception e) {
...
}
}
}
(5) Then, your kb thread initially must wait for the signal that
connection has completed, then waits for input. When input occurs,
it synchronizes on the DataWrapper, adds data to it, and then
registers the socket for writes, and wakes up the selector.
[IIRC, in Java 1.4 there's a threading issue that means you
have to register for writes AFTER the selector.select() wakes
up-- i.e. you add the socket to some kind of list that you then
check for after selector.select() and register each channel in the
list for writes.]
Hope all that makes sense. The skeleton above is adapted from some
working code I wrote a while ago, bar any copy-and-pastos. Note that
in my case, I was connecting to multiple servers from a single client.
It's not actually that common to use NIO on a client, and from
the description of your requirements (connecting to a single server?)
I'm not sure you'll see any benefit.
Neil