In my last post we created a UDP client using Apache MINA. Lets turn the table and implement the Server side. Let's see how using Apache MINA reduces the effort to create a UDP Server.
Steps to create a UDP Server using java.net API's
- Create a Socket and listen for incoming connection
- Process each packet in a separate thread 🙂 (I hate this, unfortunately need this to have high processing rate)
- Parse and process the request and optionally send response (Lets omit this to keep things simple)
- Create a NioDatagramAcceptor
- Add an IoHandler
- Bind and make application ready to receive
- Our protocol is carrying Strings in UDP packet
- We shall not do any transformation on the packets received. We shall just dump the content
The Handler is in its basic form. Our only method of interest is messageReceived. Since we know that we are getting "String" message without any transformation, we could easily create a new string from the bytes received. A wonderful thing to note about this API is the parameter "message". This makes the API generic enough to cater to any kind of objects. If we had used a ProtocolCodec in the chain and had transformed the byte into a custom Object, we would have type-casted message to that object.
So what does 31 does. There is wonderful description of this option at http://www.unixguide.net/network/socketfaq/4.5.shtml
The main function is pretty simple. The Server is ready. You can run it, using the Client from the post Implementing UDP Client using Apache MINA