javaniochanneldatagram

DatagramChannel Server one unconnected channel and more connected channels


I'm trying to abstract NIO channels for UDP and TCP. The DatagramChannel and SocketChannel are already much alike. However i run into one problem. I'm now trying to create a DatagramChannelServer as opposed to ServerSocketChannel. What i do is i instantiare an unconnected DatagramChannel as server, on any read actions i create a new DatagramChannel which i connect to the received address. So i have the unconnected DatagramChannel that is supposed to receive incomming data from all unconnected sources and the connected DatagramChannel that receives all data from the connected source.

This however does not work, since all received data whether from a connected source or not is received by the unconnected DatagramChannel. Can you somehow prioritize the order in which keys are handles in a way that Connected DatagramChannels are prioritized above unconnected DatagramChannels? or is there another elegant solution to solve this?

At this moment i have a (in my opinion) non elegant solution which takes the data from the unconnected DatagramChannel and inserts it into the respective connected DatagramChannel. However i'd like to have a solution more fitting to the framework.

Somebody a clue on how to do this neatly?


Solution

  • What i do is i instantiare an unconnected DatagramChannel as server, on any read actions i create a new DatagramChannel which i connect to the received address.

    Why? You already have a DatagramChannel. You don't need any more.

    In the nature of UDP you should treat each request/response as a completely standalone transaction, without session context. So all you have to do is receive a datagram, compute the reply, send the reply, on the same DatagramChannel.