Created
June 23, 2012 11:24
-
-
Save purplefox/2977945 to your computer and use it in GitHub Desktop.
client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Client { | |
public static void main(String[] args) { | |
try { | |
Executor pool = Executors.newCachedThreadPool(); | |
NioClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory( | |
pool, pool); | |
// Try with multiple client boss threads | |
// NioClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory( | |
// pool, pool, 12, 12); | |
ClientBootstrap bootstrap = new ClientBootstrap(channelFactory); | |
bootstrap.setPipelineFactory(new ChannelPipelineFactory() { | |
public ChannelPipeline getPipeline() throws Exception { | |
ChannelPipeline pipeline = Channels.pipeline(); | |
pipeline.addLast("handler", new ClientHandler()); | |
return pipeline; | |
} | |
}); | |
final int num = 1000; | |
for (int i = 0; i < num; i++) { | |
final int c = i; | |
final long start = System.currentTimeMillis(); | |
ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 1234)); | |
future.addListener(new ChannelFutureListener() { | |
public void operationComplete(ChannelFuture channelFuture) throws Exception { | |
System.out.println("Connected in " + (System.currentTimeMillis() - start)); | |
if (channelFuture.isSuccess()) { | |
System.out.println("Connected successfully " + c); | |
} else { | |
channelFuture.getCause().printStackTrace(); | |
} | |
if (c == num - 1) { | |
System.out.println("DONE"); | |
} | |
} | |
}); | |
} | |
Thread.sleep(100000); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
private static class ClientHandler extends SimpleChannelUpstreamHandler { | |
@Override | |
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { | |
System.out.println("Channel connected"); | |
} | |
@Override | |
public void channelClosed(ChannelHandlerContext chctx, ChannelStateEvent e) { | |
System.out.println("Channel closed"); | |
} | |
@Override | |
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { | |
System.out.println("Message received"); | |
} | |
@Override | |
public void channelInterestChanged(ChannelHandlerContext chctx, ChannelStateEvent e) throws Exception { | |
System.out.println("Interest changed"); | |
} | |
@Override | |
public void exceptionCaught(ChannelHandlerContext chctx, ExceptionEvent e) { | |
System.out.println("Exception caught"); | |
e.getCause().printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment