I decided to make my UDPclient and UDPserver with java nio. But I don't understand several things. Here is the code
try {
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.connect(remote);
//monitoring
Selector selector = Selector.open();
//read write keys
channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
ByteBuffer buffer = ByteBuffer.allocate(1024*64);//number of bytes for channel
while (true) {
selector.select(60000);//number of channels I think
Set readyKeys = selector.selectedKeys();
if (readyKeys.isEmpty()) {
break;
}
else {
Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
if (key.isReadable( )) {
//read from buffer
channel.read(buffer);
}
if (key.isWritable()) {
//write to buffer
channel.write(buffer);
}
}
}
}
}
catch (IOException ex) {
System.err.println(ex);
}
If I write something in console the event in key.isWritable
will occur? And if server sends something event isReadable will occur?
And I don't understand how to work with my events when for example user write "GETL" or "REGR"(my own methods).
The value you pass to select
is a timeout not the number of channels.
You need to do
DatagramChannel channelFromKey = (DatagramChannel) key.channel();
not use channel
I don't understand what you mean by your own events. Read the Datagrams off the channel when that key is selected.
Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
if (key.isReadable( )) {
DatagramChannel channelFromKey =
(DatagramChannel) key.channel();
buffer.clear();
// This is a DatagramChannel receive a datagram as a whole
channelFromKey.receive(buffer);
}
If I write something in console the event in key.isWritable will occur?
No. The only events that will occur are on the channels you have registered with the selector. You haven't registered any channel to do with the console, and you can't, because only network channels are SelectableChannels, so you have to reason to expect events originating from the console to turn up via the Selector.
And if server sends something event isReadable will occur?
Yes.
And I don't understand how to work with my events when for example user write "GETL" or "REGR"(my own methods).
Nor do I. I don't even understand the question. The only events you will get from the selector are the ones that it defines, on the channels you have registered with it.