Using Camel Netty Components to manage socket routes

The netty component is a socket based Caamel communication component, which relies on the Netty project. Netty is a client server framework designed around Java NIO API which enables fast and simple development of network applications either servers or clients. The advantage of using Netty is that it greatly simplifies network programming by means of API running on the top of TCP and UDP protocols.

You can use this component to create both producer and consumer endpoints. Let’s see an example in Java DSL.

package com.sample;

 
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

 
public class TCPServer {

    public static void main(String[] args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyRouteTCPServer());
        main.run(args);
    }
}

class MyRouteTCPServer extends RouteBuilder {

    @Override
    public void configure() throws Exception {

        from("netty:tcp://localhost:8001?textline=true&sync=false").to("stream:out");

    }
}

The above example starts a TCP server listening on port 8001, using a text based format (textline=true), setting the endpoint as request-response communication (sync=false). In order to compile and execute the above Camel class, you will need netty dependencies in your project:

<dependencies>
	<dependency>
	  <groupId>org.apache.camel</groupId>
	  <artifactId>camel-core</artifactId>
	  <version>${camel.version}</version>
	</dependency>
	<dependency>
	  <groupId>org.apache.camel</groupId>
	  <artifactId>camel-spring</artifactId>
	  <version>${camel.version}</version>
	</dependency>
	<dependency>
	  <groupId>org.apache.camel</groupId>
	  <artifactId>camel-netty</artifactId>
	  <version>${camel.version}</version>
	</dependency>
</dependencies>

Now you can add a simple Java Client class to send some sample messages to our Server:

import java.io.*;
import java.net.*;

public class Client {

    public static void main(String argv[]) throws Exception {

        Socket clientSocket = new Socket("localhost", 8001);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

        outToServer.writeBytes("Hello Camel\n");

        clientSocket.close();
    }
}

The expected outcome, is to find the message (“Hello Camel”), on the Camel output console.