0
votes

I am new to Java NIO .

I have a java program which queries servers (different IPs /Ports) iteratively in a loop. But now i want to send all the packets at once instead of in a loop and then store the data received in the reply packet.

The query consists of only 1 reply packet, no further communication is required.

is this the way to do it - > Make a datagram Channel , send all packets via .send() , listen for packets and start new thread to process and store packet data.

number of servers maybe >400 . Is it better to make 400 threads or 400 datagram channels ??? Also should i use async package instead of NIO .

Would it be easier with Netty etc?

2
I would get plain NIO working first. It worth noting that while TCP is reliable, UDP is not. You have to allow for the fact that some packet may not arrive. For 400 TCP connections I would still use one thread, unless there was a good reason to do otherwise.Peter Lawrey
servers reply only to UDP. Lost packets are not a problem.user871457

2 Answers

0
votes

If you are going to use UDP, you can use one thread per server and one port for all of them. You may want to use a couple of port for different message types.

If you use just one multi-cast & port, any listener will hear all packets from any application to that IP & port.

0
votes

I'm not familiar enough to advise of NIO, but regarding replies handling - better use thread pool and channel pool.

EDIT - more explanation

You should have just one thread that listens on the port to which the servers reply. Upon receiving a reply, submit a "handle task" to a tasks queue. The next available thread will pull that task and handle it.

So, if you have more replies (=tasks) than available threads, the tasks will wait in the queue. Java has nice thread pool support under java.util.concurrent package. These limits are of course configurable.

Basically, the listner thread is performing a minimal operation of creating a handle-task and putting in a queue. If you're afraid of missing replies during that short period then you should configure more listener threads... But I doubt there's a real concern there.