Home > Uncategorized > Writing a TCP/UDP stack supporting the SIP protocol using the Grizzly Framework

Writing a TCP/UDP stack supporting the SIP protocol using the Grizzly Framework

Over the last year, I’ve had the opportunity to work (and learn!) with Ericsson on a TCP/UDP stack for supporting the SIP protocol. SIP is an interesting protocol and implementing support for it with Grizzly was quite interesting. My goal over the next few weeks is to explain how I did it using the Grizzly framework.

First, if you are new with Grizzly, I recommend you take a look at the terminology we are using. You might also wants to read about what is the SIP protocol, although for this first entry, I will focus on the transport implementation, not on SIP yet.

The first step when writing an application using Grizzly is to create the com.sun.grizzly.Controller object. This object is THE object that allow you to control the framework.

Controller controller = new Controller();

Next, we need to configure which transport we want to support. For this blog purpose, I will only explain how to support UDP and TCP, and talk about TLS later. In Grizzly, a transport is represented using the SelectorHandler interface, and the framework support by default three implementation: TCPSelectorHandler, TLSSelectorHandler and UDPSelectorHandler. By default, the Controller support TCP, but to help understanding how it works, the code below will explicitly configure the Controller to support TCP and UDP:

        TCPSelectorHandler tcpSelector = new TCPSelectorHandler();
        UDPSelectorHandler udpSelector = new UDPSelectorHandler();

So far so good 🙂 Next is to configure the thread pool we want our application to use. In Grizzly, it is possible to associate a thread pool per SelectorHandler or shared among SelectorHandler. By default, the Controller creates a shared thread pool. For this application, we gonna create a single thread pool (called Pipeline) shared between the TCPSelectorHandler and UDPSelectorHandler.

        Pipeline mySharedPipeline = new DefaultPipeline());

The next optional object to configure is the ProtocolChainInstanceHandler. The way Grizzly works is when a connection is made to one of its SelectorHandler, it accepts the connection (OP_ACCEPT) and then delegate the handling of the read/write/connect operations to what we call a ProtocolChain. A ProtocolChain implement the “Chain of Responsibility” pattern (for more info, take a look at the classic “Gang of Four” design patterns book). Towards that end, the Chain API models a computation as a series of “protocol filter” that can be combined into a “protocol chain”. The API for ProtocolFilter consists of a two methods (execute(Context) and postExecute(Context)) which is passed a “protocol context” parameter containing the dynamic state of the computation, and whose return value is a boolean that determines whether or not processing for the current chain has been completed (false), or whether processing should be delegated to the next ProtocolFilter in the chain (true).

ProtocolFilter can be stateless or stateful. By stateless, I mean an instance of ProtocolFilter can be executed by several threads simultaneously. By stateful, I means an instance of ProtocolFilter is not thread safe, so we usually need to create one instance per thread. Based on what your application does, you might want to configure the “state” of you ProtocolChain: stateful or stateless. This is what the ProtocolChainInstanceHandler is for. The Controller will invoke that object every time it needs to execute an operation. For our application, let’s assume we define a stateless ProtocolChain/ProtocolFilter:

        ProtocolChainInstanceHandler pciHandler =
                new ProtocolChainInstanceHandler() {

            final private ProtocolChain protocolChain = new DefaultProtocolChain();

            public ProtocolChain poll() {
                return protocolChain;

            public boolean offer(ProtocolChain instance) {
                return true;

Next, we need to add our protocol specific implementation via ProtocolFilter. Grizzly ships with a ReadFilter than can be used to read bytes, independently of the transport used (UDP or TCP). Mainly, the ReadFilter reads the available bytes, and pass the control over the next ProtocolFilter. For the purpose of this blog, let’s add an echo ProtocolFilter (EchoFilter) that return the bytes sent by the client:

        ProtocolChain protocolChain = pciHandler.poll();
        protocolChain.addFilter(new ReadFilter());
        protocolChain.addFilter(new EchoFilter());

Technically, the EchoFilter just do:

    public boolean execute(Context ctx) throws IOException {
        final WorkerThread workerThread = ((WorkerThread)Thread.currentThread());
        ByteBuffer buffer = workerThread.getByteBuffer();
        if (buffer.hasRemaining()) {
            // Depending on protocol perform echo
            SelectableChannel channel = ctx.getSelectionKey().channel();
            try {
                if (ctx.getProtocol() == Controller.Protocol.TCP) { // TCP case
                    OutputWriter.flushChannel(channel, buffer);
                } else if (ctx.getProtocol() == Controller.Protocol.UDP) {  // UDP case
                    DatagramChannel datagramChannel = (DatagramChannel) channel;
                    SocketAddress address = (SocketAddress) 
                    OutputWriter.flushChannel(datagramChannel, address, buffer);
            } catch (IOException ex) {
                // Store incoming data in byte[]
                byte[] data = new byte[buffer.remaining()];
                int position = buffer.position();
                        "Exception. Echo \"" + new String(data) + "\"");
                throw ex;
        return false;

Without going into too much details, this ProtocolFilter just take the ByteBuffer that contains the client’s bytes, and write it back using a temporary Selector trick (kind of a blocking write operation). Finally, we are ready to start our application:


There is other configurable interfaces with Grizzly (like how idles connections are closed using a SelectionKeyHandler), but for now we gonna just use the default. That’s it, we have now a server that listen for UDP and TCP requests :-). To recap, here is complete source code:

package com.sun.grizzly.utils;
      1 package com.sun.grizzly.utils;
      3 import com.sun.grizzly.Controller;
      4 import com.sun.grizzly.DefaultPipeline;
      5 import com.sun.grizzly.Pipeline;
      6 import com.sun.grizzly.ProtocolChain;
      7 import com.sun.grizzly.ProtocolChainInstanceHandler;
      8 import com.sun.grizzly.TCPSelectorHandler;
      9 import com.sun.grizzly.UDPSelectorHandler;
     10 import com.sun.grizzly.filter.EchoFilter;
     11 import com.sun.grizzly.filter.ReadFilter;
     13 public class SipServerDemo {
     15     public void startSIPServerDemo(){
     17         Controller controller = new Controller();
     19         TCPSelectorHandler tcpSelector = new TCPSelectorHandler();
     20         tcpSelectorHandler.setPort(8080);
     21         controller.addSelectorHandler(tcpSelector);
     23         UDPSelectorHandler udpSelector = new UDPSelectorHandler();
     24         udpSelectorHandler.setPort(8080);
     25         controller.addSelectorHandler(udpSelector);
     27         Pipeline mySharedPipeline = new DefaultPipeline());
     28         pipeline.setMaxThreads(5);
     30         controller.setPipeline(mySharedPipeline);
     32         ProtocolChainInstanceHandler pciHandler =
     33                 new ProtocolChainInstanceHandler() {
     35             final private ProtocolChain protocolChain = new DefaultProtocolChain();
     37             public ProtocolChain poll() {
     38                 return protocolChain;
     39             }
     41             public boolean offer(ProtocolChain instance) {
     42                 return true;
     43             }
     44         };
     45         controller.setProtocolChainInstanceHandler(pciHandler);
     47         ProtocolChain protocolChain = pciHandler.poll();
     48         protocolChain.addFilter(new ReadFilter());
     49         protocolChain.addFilter(new EchoFilter());
     51         controller.start();
     52     }
     54 }

Wow, that not that complicated 🙂 You can browse the Grizzly code online if you are interested about Grizzly’s internal here. My next blog will describe how to implement a client side TCP/UDP connector using the ConnectorHandler (needed by the SIP protocol), and discuss the details of how the SIP protocol can be implemented via a ProtocolFilter. A+

Part II can be read here.

_uacct = “UA-3111670-1”;


Categories: Uncategorized
  1. karthik
    December 17, 2010 at 4:23 pm

    Hai your post had relavent information about i was searching for, I would like to know the status and possibility of building SIP stack built using websockets……

    • December 20, 2010 at 1:00 pm

      Salut, I’m no longer on Grizzly & Sun, Please go to users@grizzly.java.net and ask the question there. I’m sure they will be interested.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: