thufir

Untitled

Jul 20th, 2014
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.40 KB | None | 0 0
  1. package net.bounceme.dur.netty;
  2.  
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.ChannelOption;
  7. import io.netty.channel.ChannelPipeline;
  8. import io.netty.channel.EventLoopGroup;
  9. import io.netty.channel.nio.NioEventLoopGroup;
  10. import io.netty.channel.socket.SocketChannel;
  11. import io.netty.channel.socket.nio.NioSocketChannel;
  12. import io.netty.handler.logging.LogLevel;
  13. import io.netty.handler.logging.LoggingHandler;
  14. import io.netty.handler.ssl.SslContext;
  15. import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
  16.  
  17. public final class EchoClient {
  18.  
  19.     private boolean ssl;
  20.     private String host;
  21.     private int port;
  22.     static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
  23.     private final MyProps p = new MyProps();
  24.  
  25.     public static void main(String[] args) throws Exception {
  26.         new EchoClient().runServer();
  27.     }
  28.  
  29.     private void runServer() throws Exception {
  30.         ssl = p.getSSL();
  31.         host = p.getHost();
  32.         port = p.getServerPort();
  33.         final SslContext sslCtx;
  34.         if (ssl) {
  35.             sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
  36.         } else {
  37.             sslCtx = null;
  38.         }
  39.  
  40.         EventLoopGroup group = new NioEventLoopGroup();
  41.         try {
  42.             Bootstrap b = new Bootstrap();
  43.             b.group(group)
  44.                     .channel(NioSocketChannel.class)
  45.                     .option(ChannelOption.TCP_NODELAY, true)
  46.                     .handler(new ChannelInitializer<SocketChannel>() {
  47.                         @Override
  48.                         public void initChannel(SocketChannel ch) throws Exception {
  49.                             ChannelPipeline p = ch.pipeline();
  50.                             if (sslCtx != null) {
  51.                                 p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
  52.                             }
  53.                             p.addLast(new LoggingHandler(LogLevel.INFO));
  54.                             p.addLast(new PingPongClientHandler());
  55.                         }
  56.                     });
  57.             ChannelFuture f = b.connect(host, port).sync();
  58.             f.channel().closeFuture().sync();
  59.         } finally {
  60.             group.shutdownGracefully();
  61.         }
  62.     }
  63.  
  64.     static int getSize() {
  65.         return SIZE;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment