Its been a while that I wrote on Apache MINA. Please refer to my post collection on Apache MINA.
In this post, I have tried to capture briefly on how to implement a UDP Client using Apache MINA. We shall concentrate on keeping our scope limited to sending data over UDP. In Subsequent posts, we shall see how we can enhance this UDP Client to send SNMP Traps.
In brief, these are the steps we need to perform to send a UDP packet
- Create a Datagram Socket
- Create a Datagram Packet
- Send the packet
- Create a NioDatagramConnector instance
- Add an IoHandler (we can use an IoHandlerAdapter, as for this example we don’t need to use all the API’s)
- Connect the NioDatagramConnector
- Get the session
- Write the data onto the session
Lets see the Code in detail now. We have maintained the Session at the class level, assuming that we may reuse the session for sending packets, if session is still active. At line 25, we check if the session is active or not. If inactive we initiate the connection.
Line 28, creates an instance of NioDatagramConnector
Line 31, add an IoHandler to the NioDatagramConnector on Line 28. In MINA terminology, IoHandler contains the code where Business logic of an Application resides. In our case its a pure Adapter, with only log statements inside the functions.
Line 32, a call to connect(), returns an reference to ConnectFuture. The call, starts the connection operation, in a separate thread and returns to the caller. To cater to this asynchronous behaviour, we add an IoFutureListener, to returned ConnectFuture reference. Out there (Line 38-43), we just check if the connection is OK, we get the session from it. Line 39, signals that connection is connected and its safe to get the session for writing data.
The connect code is complete. Lets see how to send the data.
The send function is pretty simple. We just create an IoBuffer and call write on the session. We have called connect() on Line 59, just to ensure that the connection is alive. If it isn’t, it shall create a connection and return a session back.
NOTE: This code is in its very simple form. There can be various mechanism to handle Session (based on destination etc). Also, please be aware of the asynchronous behaviour of the NioDatagramConnector connect() API. If the connection is not complete in time, you might see a null pointer at Line 67 :-(. But this is usually the case. For production code, it is advisable to ensure that session is never null.
That’s it, out UDP client is ready. To create an SNMP Trap sender, we just need to pass Trap byte array to send() and we are done. Will try to post that article soon.