Using Grizzly for Scalable Server Applications
It has always been a pain to develop scalable and robust servers with the Java NIO libraries. Recently there are several open source frameworks like Grizzly, Apache Mina, or JBoss Netty to address this problem.
Using the Grizzly NIO framework, it is now easier to develop scalable servers using the NIO capabilities of the Java platform. Grizzly provides default implementations for TCP, UDP and TLS/SSL transports, and since almost everything is customizable, it is also easy to develop servers for custom protocols.
Creating a TCP server with Grizzly is easy:
TCPNIOTransport transport = TransportFactory.getInstance().createTCPTransport();
transport.getFilterChain().add(new TransportFilter());
transport.getFilterChain().add(new MessageProcessor());// business logic
transport.bind(localhost, port);// bind to transport address
transport.start();// start serving
We just need to create a TCPNIOTransport instance, and add a default filter which is responsible for delegating I/O event processing to the Transport’s specific transport filter, and we add another filter object which is responsible for the business logic. Finally, we bind the server to the transport address, and start serving clients.
In our example, the MessageProcessor instance only implements
public NextAction handleRead(FilterChainContext ctx, NextAction nextAction)
throws IOException
method which is responsible for executing the business logic. In this method, we perform the necessary computations, and send the response message to the client issuing the request:
String string = getAvailableSpace().toString();//message to return
ByteBufferWrapper send = new ByteBufferManager().allocate(ONE_KB);
send.put(string.getBytes());
streamWriter.writeBuffer(send);
On the client side, we just need to connect to the server transport address, and simply send the message over the channel:
TCPNIOTransport transport = TransportFactory.getInstance().createTCPTransport();
transport.start();
Future future = transport.connect(localhost, port);
connection = future.get(10, TimeUnit.SECONDS);//wait ten seconds for connect operation
writer = connection.getStreamWriter();
writer.writeByteArray(severalBytesToSend);
reader = connection.getStreamReader();
byte[] receivedBytes = new byte[ONE_KB];// 1 KB for read buffer
reader.readByteArray(receivedBytes);
//now process receivedBytes
That is it! Although it seems simple, for a production application we really need to handle various failures that may occur in many stages of the applications e.g., when reading, connecting, writing… You can download the source code for the example here.
Additional Examples:
https://grizzly.dev.java.net/tutorials/tutorial-framework-filter-sample/index.html
About this entry
You’re currently reading “ Using Grizzly for Scalable Server Applications ,” an entry on Sirius ICT
- Published:
- 11.29.09 / 3pm
No comments
Jump to comment form | comments rss [?] | trackback uri [?]