Skip to content

Instantly share code, notes, and snippets.

@vlaadbrain
Created September 28, 2012 17:37
Show Gist options
  • Save vlaadbrain/3801188 to your computer and use it in GitHub Desktop.
Save vlaadbrain/3801188 to your computer and use it in GitHub Desktop.
Netty Example Client
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
public class NettyExampleClient extends SimpleChannelHandler {
private String [] SYMBOLS = new String[]{"SPY", "BAC", "XOM"};
private void subscribe(ChannelHandlerContext ctx) {
for (String symbol : SYMBOLS)
ctx.getChannel().write('w' + symbol);
}
private void processQuote(String ... fields) {}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
ChannelBuffer buf = ((ChannelBuffer) e.getMessage()).copy();
String message = new String(buf.array());
String [] fields = message.split(",");
if (fields.length > 0) {
if (fields[0].equals("Q")) {
this.processQuote(fields);
} else if (fields[0].equals("S")) {
if (fields[1].equals("CUST"))
this.subscribe(ctx);
}
}
ctx.sendUpstream(e);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getCause().printStackTrace();
e.getChannel().close();
}
public static void main(String[] args) {
ChannelFactory factory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ClientBootstrap bootstrap = new ClientBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
return Channels.pipeline(
new DelimiterBasedFrameDecoder(500,Delimiters.lineDelimiter()),
new NettyExampleClient());
}
});
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 5009));
future.awaitUninterruptibly();
if (!future.isSuccess()) {
future.getCause().printStackTrace();
}
future.getChannel().getCloseFuture().awaitUninterruptibly();
factory.releaseExternalResources();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment