Friday, April 22, 2011

socat is so cool...

I was helping someone the other day figure out how to use Camel to create a TCP/IP proxy, and I was trying to figure out the best way to test. Hiram Chirino pointed me at the socat utility, which is so super geeky cool that I am inspired to post about it...

I installed socat on my Mac using MacPorts

> sudo ports install socat

The full code is here on GitHub https://github.com/scranton/camel-example-tcpipproxy.

The Camel route is straightforward. It uses Camel-Mina to both listen on port 5000 and to connect to a request-response (InOut) service on port 5001.



When you run this route, you can use socat as both the back-end service (echo style) and as a client. To start it as a back-end echo service, which will start a TCP/IP listener on port 5001 and will echo all messages sent to it (that's what 'PIPE' does).

> socat PIPE TCP4-LISTEN:5001


To use socat as a TCP/IP client, run

> socat - tcp:localhost:5001

Now any text you type in the Terminal where you started the client will be echo'd back to you - after it goes to and from the socat echo service. You can test this by stopping the socat echo service and seeing how the client reacts.

Back to the Camel proxy... To test, after you start the socat echo server, you'd start the Camel route

> mvn install camel:run

This will start the Camel route standalone (the full example can also be deployed within ServiceMix), with a TCP/IP listener on port 5000 and a connection to the echo service on port 5001. Now you can start the socat client, but this time against port 5000 (the Camel proxy)

> socat - tcp:localhost:5000

Now your text messages will run through the Camel proxy before going to the back end echo service; the Camel route will log each message that it proxies.

A quick example of a cool TCP/IP utility, and how to use the powerful Camel framework to proxy anything... Thanks for the tip Hiram!