Showing posts with label TCP. Show all posts
Showing posts with label TCP. Show all posts

Monday, July 23, 2007

Using Grizzly to read TCP Packets

Recently I had the need to be able to listen on a port and read TCP packets that were sent from a logger (java.util.SocketHandler), and I wanted to utilize the Grizzly framework to do this. With some help from the Grizzly team I was able to accomplish this and thought I would share what I did. The first thing I had to do was write a main that could connect to a port and receive TCP packets, it looked something like the following:

public class TCPProcessor {
public static void main(String[] args) throws Exception {
int port = Integer.getInteger(args[0]);

Controller controller = new Controller();
TCPSelectorHandler tcpHandler = new TCPSelectorHandler();
final MyProtocolFilter filter = new MyProtocolFilter();

tcpHandler.setPort(port);
controller.setProtocolChainInstanceHandler(new DefaultProtocolChainInstanceHandler() {
public ProtocolChain poll() {
ProtocolChain protocolChain = protocolChains.poll();

if (protocolChain == null) {
protocolChain = new DefaultProtocolChain();
protocolChain.addFilter(new ReadFilter());
protocolChain.addFilter(filter);
}

return protocolChain;
}
});
controller.addSelectorHandler(tcpHandler);
controller.start();
}
}
Now that I have my main listening, I need to write the Filter that will handle the processing of the data packet. With the ProtocolChain, the ReadFilter will read the TCP packets and pass it to the next filter in the chain, which is were I need to process my data. My filter will look something like the following:
public class MyProtocolFilter implements ProtocolFilter {
public boolean execute(Context context) {
final WorkerThread workerThread = ((WorkerThread)Thread.currentThread());
String message = "";
ByteBuffer buffer = workerThread.getByteBuffer();
buffer.flip();

if(buffer.hasRemaining()) {
byte[] data = new byte[buffer.remaining()];
int position = buffer.position();
buffer.get(data);
buffer.position(position);
message = new String(data);
}
System.out.println("New message being read, message is: " + message);
buffer.clear();
return false;
}

public boolean postExecute(Context context) throws IOException {
return true;
}
}

So now you could whip up a test to send some data over TCP and the Processor will read the packets and print the message out.