@Override
  public void run() {

    EventLoopGroup group = new NioEventLoopGroup();

    try {

      Bootstrap b = new Bootstrap();

      b.group(group); // group 组
      b.channel(NioSocketChannel.class); // channel 通道
      b.option(ChannelOption.TCP_NODELAY, true); // option 选项
      b.handler(new ChildChannelHandler()); // handler 处理

      // 发起异步链接
      f = b.connect(BaseConfig.inetHost, BaseConfig.inetPort);

      // 等待客户端链路关闭
      f.channel().closeFuture().sync();

    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      group.shutdownGracefully();
    }
  }
Exemple #2
0
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
      sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                  }
                  p.addLast(new DiscardClientHandler());
                }
              });

      // Make the connection attempt.
      ChannelFuture f = b.connect(HOST, PORT).sync();

      // Wait until the connection is closed.
      f.channel().closeFuture().sync();
    } finally {
      group.shutdownGracefully();
    }
  }
  /** 初始化 */
  private void init() {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      //			final LogLevel loglevel = LogLevel.valueOf(p.getProperty("upa_loglevel").toUpperCase());
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline()
                      .addLast(
                          new TcpCodec(),
                          //									new LoggingHandler(loglevel),
                          new TcpClientHandler());
                }
              });

      ChannelFuture cf = b.connect("127.0.0.1", 21108).sync();
      // cf.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      logger.error("client初始化失败:", e); // $NON-NLS-1$
      e.printStackTrace();
    } finally {
      // group.shutdownGracefully();
    }
    logger.info("client初始化完成");
  }
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // TODO: Suspend incoming traffic until connected to the remote host.
    //       Currently, we just keep the inbound traffic in the client channel's outbound buffer.
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop())
        .channel(NioSocketChannel.class)
        .remoteAddress(remoteHost, remotePort)
        .handler(new HexDumpProxyBackendHandler(inboundChannel));

    ChannelFuture f = b.connect();
    outboundChannel = f.channel();
    f.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              // Connection attempt succeeded:
              // TODO: Begin to accept incoming traffic.
            } else {
              // Close the connection if the connection attempt has failed.
              inboundChannel.close();
            }
          }
        });
  }
  public void connect(int port, String host) throws Exception {
    // 配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(
              new ChannelInitializer<SocketChannel>() // 匿名内部类
              {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline().addLast(new TimeClientHandler());
                }
              });

      // 发起异步连接操作
      ChannelFuture f = b.connect(host, port).sync();

      // 等待客户端链路关闭
      f.channel().closeFuture().sync();
    } finally {
      // 优雅退出,释放NIO线程组
      group.shutdownGracefully();
    }
  }
  public void connect() throws Exception {
    System.out.println("consumer client start connect");
    group = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(
            new ChannelInitializer<SocketChannel>() {
              @Override
              protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ObjectEncoder());
                ch.pipeline()
                    .addLast(new ObjectDecoder(1024 * 1024, ClassResolvers.cacheDisabled(null)));
                ch.pipeline().addLast(new ConsumerHandler());
              }
            });

    channelFuture = b.connect(host, port);
    channelFuture.awaitUninterruptibly();
    assert channelFuture.isDone();

    if (channelFuture.isCancelled()) {

    } else if (!channelFuture.isSuccess()) {
      throw new RuntimeException(channelFuture.cause().getCause());
    }
  }
  public void connect(int port, String host) throws Exception {
    // 配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                  ch.pipeline()
                      .addLast(
                          new ProtobufDecoder(
                              SubscribeRespProto.SubscribeResp.getDefaultInstance()));
                  ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                  ch.pipeline().addLast(new ProtobufEncoder());
                  ch.pipeline().addLast(new SubReqClientHandler());
                }
              });

      // 发起异步连接操作
      ChannelFuture f = b.connect(host, port).sync();

      // 当代客户端链路关闭
      f.channel().closeFuture().sync();
    } finally {
      // 优雅退出,释放NIO线程组
      group.shutdownGracefully();
    }
  }
  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioDatagramChannel.class)
          .option(ChannelOption.SO_BROADCAST, true)
          .handler(new QuoteOfTheMomentClientHandler());

      Channel ch = b.bind(0).sync().channel();

      // Broadcast the QOTM request to port 8080.
      ch.write(
              new DatagramPacket(
                  Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                  new InetSocketAddress("255.255.255.255", port)))
          .flush()
          .sync();

      // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
      // response is received.  If the channel is not closed within 5 seconds,
      // print an error message and quit.
      if (!ch.closeFuture().await(5000)) {
        System.err.println("QOTM request timed out.");
      }
    } finally {
      group.shutdownGracefully();
    }
  }
  public void init(ChannelPipelineFactory factory) throws Exception {
    id =
        String.format("%1$020d", Math.abs(new Random(System.currentTimeMillis()).nextLong()))
            .getBytes();

    group = new OioEventLoopGroup();
    connectionlessBootstrap = new Bootstrap();
    connectionlessBootstrap.group(group);
    connectionlessBootstrap.option(ChannelOption.SO_BROADCAST, true);
    connectionlessBootstrap.handler(factory);
    connectionlessBootstrap.channel(OioDatagramChannel.class);
    ;
    datagramChannel =
        (DatagramChannel)
            connectionlessBootstrap.bind(new InetSocketAddress(mcastGroupPort)).sync().channel();
    multicastAddress = new InetSocketAddress(mcastGroupIp, mcastGroupPort);
    NetworkInterface networkInterface =
        NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddress));
    // for (Enumeration nifs = NetworkInterface.getNetworkInterfaces();
    // nifs.hasMoreElements(); )
    datagramChannel.joinGroup(multicastAddress, null); // (NetworkInterface)
    // nifs.nextElement());
    init = true;
    if (debug) factory.debug();
  }
Exemple #10
0
 public void start() throws InterruptedException, URISyntaxException {
   EventLoopGroup group = new NioEventLoopGroup();
   try {
     Bootstrap b = new Bootstrap();
     b.group(group).channel(NioSocketChannel.class);
     b.handler(
         new ChannelInitializer<Channel>() {
           @Override
           protected void initChannel(Channel ch) throws Exception {
             ChannelPipeline pipeline = ch.pipeline();
             pipeline.addLast("decoder", new RtspResponseDecoder());
             pipeline.addLast("encoder", new RtspRequestEncoder());
             pipeline.addLast("aggregator", new HttpObjectAggregator(1024 * 1024 * 64));
             pipeline.addLast("handler", new ResponseHandler());
           }
         });
     b.option(ChannelOption.SO_KEEPALIVE, true);
     ChannelFuture channelFutrue = b.connect(host, port).sync();
     if (channelFutrue.isSuccess()) {
       channel = channelFutrue.channel();
       URI uri = new URI("rtsp://127.0.0.1:554/hello-world");
       HttpRequest request = this.buildOptionsRequest(uri.toASCIIString());
       this.send(request);
       channel.closeFuture().sync();
     }
   } finally {
     // 优雅退出,释放NIO线程组
     group.shutdownGracefully();
   }
 }
Exemple #11
0
 public void run() {
   // Configure the client.
   final ThreadFactory connectFactory = new UtilThreadFactory("connect");
   final NioEventLoopGroup connectGroup =
       new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER);
   try {
     final Bootstrap boot = new Bootstrap();
     boot.group(connectGroup)
         .channelFactory(NioUdtProvider.BYTE_CONNECTOR)
         .handler(
             new ChannelInitializer() {
               @Override
               protected void initChannel(Channel ch) throws Exception {
                 ch.pipeline()
                     .addLast(new LoggingHandler(LogLevel.INFO), new ModemClientHandler());
               }
             });
     // Start the client.
     final ChannelFuture f = boot.connect(host, port).sync();
     f.channel().closeFuture().sync();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     // Shut down the event loop to terminate all threads.
     connectGroup.shutdownGracefully();
   }
 }
  public void connection(String host, int port) throws Exception {
    // 定义主线程组,处理轮询
    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    try {
      // 这是客户端的启动类
      Bootstrap bs = new Bootstrap();
      // 设置线程组
      bs.group(bossGroup)
          // 设置option参数
          .option(ChannelOption.TCP_NODELAY, true)
          // 设置客户端SocketChannel
          .channel(NioSocketChannel.class)
          // 设置客户端处理器
          .handler(
              new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline().addLast(new TimeClientHandler());
                }
              });
      // 连接到服务器端
      ChannelFuture future = bs.connect(host, port).sync();
      future.channel().closeFuture().sync();
    } finally {
      // 优雅退出
      bossGroup.shutdownGracefully();
    }
  }
Exemple #13
0
  private static void connect() throws InterruptedException {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    ChannelFuture future = null;
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline().addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
                  ch.pipeline().addLast(new CustomEncoder());
                  ch.pipeline().addLast(new CustomClientHandler());
                  ch.pipeline().addLast(new HeartBeatClientHandler());
                }
              });

      future = b.connect(HOST, PORT).sync();
      future.channel().writeAndFlush("Hello Netty Server ,I am a common client");
      future.channel().closeFuture().sync();
    } finally {
      group.shutdownGracefully();
      //			if (null != future) {
      //				if (future.channel() != null && future.channel().isOpen()) {
      //					future.channel().close();
      //				}
      //			}
      System.out.println("准备重连");
      connect();
      System.out.println("重连成功");
    }
  }
  public void initialize(String baseUrl, String username, String password)
      throws URISyntaxException {
    this.username = username;
    this.password = password;
    group = new NioEventLoopGroup();
    baseUri = new URI(baseUrl);
    String protocol = baseUri.getScheme();
    if (!"http".equals(protocol)) {
      throw new IllegalArgumentException("Unsupported protocol: " + protocol);
    }
    // Bootstrap is the factory for HTTP connections
    bootStrap = new Bootstrap();
    bootStrap.group(group);
    bootStrap.channel(NioSocketChannel.class);
    bootStrap.handler(
        new ChannelInitializer<SocketChannel>() {

          @Override
          public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("http-codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(MAX_HTTP_REQUEST_KB * 1024));
            pipeline.addLast("http-handler", new NettyHttpClientHandler());
          }
        });
  }
Exemple #15
0
  public void run() throws Exception {
    // Configure the client.
    Bootstrap b = new Bootstrap();
    try {
      b.group(new NioEventLoopGroup())
          .channel(new NioSocketChannel())
          .option(ChannelOption.TCP_NODELAY, true)
          .remoteAddress(new InetSocketAddress(host, port))
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline()
                      .addLast(
                          new LoggingHandler(LogLevel.INFO),
                          new EchoClientHandler(firstMessageSize));
                }
              });

      // Start the client.
      ChannelFuture f = b.connect().sync();

      // Wait until the connection is closed.
      f.channel().closeFuture().sync();
    } finally {
      // Shut down the event loop to terminate all threads.
      b.shutdown();
    }
  }
Exemple #16
0
  public static void main(String[] args) throws Exception {

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  p.addLast(new MsgDecoder());
                  p.addLast(new MsgEncoder());
                  p.addLast(new EchoClientHandler());
                }
              });

      // Start the client.
      ChannelFuture f = b.connect("127.0.0.1", 80).sync();

      // Wait until the connection is closed.
      f.channel().closeFuture().sync();
    } finally {
      // Shut down the event loop to terminate all threads.
      group.shutdownGracefully();
    }
  }
Exemple #17
0
  public static void main(String[] args) throws InterruptedException {
    String host = "localhost";
    int port = 8080;

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      Bootstrap b = new Bootstrap();
      b.group(workerGroup);
      b.channel(NioSocketChannel.class);
      b.option(ChannelOption.SO_KEEPALIVE, true);
      b.handler(
          new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler());
            }
          });

      ChannelFuture f = b.connect(host, port).sync();
      f.channel().closeFuture().sync();
    } finally {
      workerGroup.shutdownGracefully();
    }
  }
Exemple #18
0
  public void run(URI uri) throws Exception {
    int port = uri.getPort() > 0 ? uri.getPort() : BaseTestConfig.HTTPS_PORT;
    String host = uri.getHost();

    // Configure SSL context if necessary.
    final SslContext sslCtx;
    sslCtx =
        SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    httpsInitializer = generateHttpsInitializer(sslCtx);
    try {
      Bootstrap b = new Bootstrap();
      b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
      b.group(group).channel(NioSocketChannel.class).handler(httpsInitializer);

      // Make the connection attempt.
      startTime = System.nanoTime();
      Channel ch = b.connect(host, port).sync().channel();
      localAddress = ch.localAddress();
      remoteAddress = ch.remoteAddress();

      sendRequests(uri.toURL(), ch);

      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      endTime = System.nanoTime();
      long duration = endTime - startTime;
      logger.info(String.format("connection duration: %,dns (%d)", duration, duration));
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
Exemple #19
0
  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      String protocol = uri.getScheme();
      if (!"ws".equals(protocol)) {
        throw new IllegalArgumentException("Unsupported protocol: " + protocol);
      }

      HttpHeaders customHeaders = new DefaultHttpHeaders();
      customHeaders.add("MyHeader", "MyValue");

      // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
      // If you change it to V00, ping is not supported and remember to change
      // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
      final WebSocketClientHandler handler =
          new WebSocketClientHandler(
              WebSocketClientHandshakerFactory.newHandshaker(
                  uri, WebSocketVersion.V13, null, false, customHeaders));

      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline pipeline = ch.pipeline();
                  pipeline.addLast("http-codec", new HttpClientCodec());
                  pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
                  pipeline.addLast("ws-handler", handler);
                }
              });

      System.out.println("WebSocket Client connecting");
      Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
      handler.handshakeFuture().sync();

      // Send 10 messages and wait for responses
      System.out.println("WebSocket Client sending message");
      for (int i = 0; i < 10; i++) {
        ch.writeAndFlush(new TextWebSocketFrame("Message #" + i));
      }

      // Ping
      System.out.println("WebSocket Client sending ping");
      ch.writeAndFlush(
          new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] {1, 2, 3, 4, 5, 6})));

      // Close
      System.out.println("WebSocket Client sending close");
      ch.writeAndFlush(new CloseWebSocketFrame());

      // WebSocketClientHandler will close the connection when the server
      // responds to the CloseWebSocketFrame.
      ch.closeFuture().sync();
    } finally {
      group.shutdownGracefully();
    }
  }
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap bootstrap = new Bootstrap();
    bootstrap
        .group(inboundChannel.eventLoop())
        .channel(ctx.channel().getClass())
        .handler(
            new ChannelInitializer<SocketChannel>() {
              @Override
              public void initChannel(SocketChannel ch) throws Exception {
                // Create a default pipeline implementation.
                ChannelPipeline pipeline = ch.pipeline();

                // add logging
                if (logger.isDebugEnabled()) {
                  pipeline.addLast("logger", new LoggingHandler("                -->"));
                }

                // add HTTPS proxy -> server support
                if (secure) {
                  SSLEngine engine = SSLFactory.sslContext().createSSLEngine();
                  engine.setUseClientMode(true);
                  pipeline.addLast("proxy -> server ssl", new SslHandler(engine));
                }

                // add handler
                pipeline.addLast(
                    new ProxyRelayHandler(
                        inboundChannel,
                        bufferedCapacity,
                        new RequestInterceptor(),
                        "                -->"));
              }
            })
        .option(ChannelOption.AUTO_READ, false);
    ChannelFuture channelFuture = bootstrap.connect(remoteSocketAddress);
    outboundChannel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              channelBuffer.clear();
              bufferedMode = bufferedCapacity > 0;
              flushedBuffer = false;
              // connection complete start to read first data
              inboundChannel.read();
            } else {
              // Close the connection if the connection attempt has failed.
              inboundChannel.close();
            }
          }
        });
  }
  public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if ("http".equalsIgnoreCase(scheme)) {
        port = 80;
      } else if ("https".equalsIgnoreCase(scheme)) {
        port = 443;
      }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
      System.err.println("Only HTTP(S) is supported.");
      return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
      sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new HttpDownloadertInitializer(sslCtx, handler));
      // Make the connection attempt.
      Channel ch = b.connect(host, port).sync().channel();
      // Prepare the HTTP request.
      HttpRequest request =
          new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
      HttpHeaders headers = request.headers();
      headers.set(HttpHeaders.Names.HOST, host);
      headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
      // Set some example cookies.
      headers.set(
          HttpHeaders.Names.COOKIE,
          ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
      ch.writeAndFlush(request);
      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      Thread.sleep(1000);
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
 @After
 public void teardown() throws Exception {
   serverChannel.close().sync();
   Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, MILLISECONDS);
   Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, MILLISECONDS);
   Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, MILLISECONDS);
   serverGroup.sync();
   serverChildGroup.sync();
   clientGroup.sync();
 }
  public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    // final LocalAddress addr = new LocalAddress(PORT);
    final InetAddress HOST = InetAddress.getByName("192.168.220.128");
    // final InetSocketAddress addr = InetSocketAddress.createUnresolved("192.168.220.128",
    // Integer.parseInt(PORT));
    NioEventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK

    final SslContext sslCtx = null;

    try {

      Bootstrap b = new Bootstrap();
      b.group(clientGroup)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  // p.addLast(new LoggingHandler(LogLevel.INFO));
                  p.addLast(new LocalEchoClientHandler());
                }
              });

      // Start the client.
      ChannelFuture f = b.connect(HOST, PORT).sync();

      ByteBuf subsequentMessage = null;
      byte[] bytes = null;
      Channel ch = b.connect(HOST, PORT).channel();
      String line = null;
      System.out.println("Feel free to chat here");
      while (true) {
        line = new BufferedReader(new InputStreamReader(System.in)).readLine();
        if (line.equalsIgnoreCase("quit") || !ch.isActive()) {
          System.out.println("Prepare to close the connection.");
          break;
        }
        subsequentMessage = Unpooled.buffer();
        bytes = line.getBytes();
        subsequentMessage.writeBytes(bytes);

        ch.writeAndFlush(subsequentMessage);
      }

      // Wait until the connection is closed.
      f.channel().closeFuture().sync();

    } finally {
      clientGroup.shutdownGracefully();
      System.out.println("Client closed");
    }
  }
  @Override
  public WsClientConnection connect(
      final HttpResponseHandler callback, final String url, final List<HttpParam> lParamQuery)
      throws RestException {
    Bootstrap wsBootStrap = new Bootstrap();
    wsBootStrap.group(group);
    wsBootStrap.channel(NioSocketChannel.class);
    wsBootStrap.handler(
        new ChannelInitializer<SocketChannel>() {

          @Override
          public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("http-codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(MAX_HTTP_REQUEST_KB * 1024));
            pipeline.addLast(
                "ws-handler", new NettyWSClientHandler(getWsHandshake(url, lParamQuery), callback));
          }
        });
    final ChannelFuture cf = wsBootStrap.connect(baseUri.getHost(), baseUri.getPort());
    cf.addListener(
        new ChannelFutureListener() {

          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              callback.onChReadyToWrite();
              // Nothing - handshake future will activate later
              /*Channel ch = future.channel();
              NettyWSClientHandler handler = (NettyWSClientHandler) ch.pipeline().get("ws-handler");
              handler.handshakeFuture.sync();*/
            } else {
              callback.onFailure(future.cause());
            }
          }
        });
    // Provide disconnection handle to client
    return new WsClientConnection() {

      @Override
      public void disconnect() throws RestException {
        Channel ch = cf.channel();
        if (ch != null) {
          ch.writeAndFlush(new CloseWebSocketFrame());
          // NettyWSClientHandler will close the connection when the server
          // responds to the CloseWebSocketFrame.
          try {
            ch.closeFuture().sync();
          } catch (InterruptedException e) {
            throw new RestException(e);
          }
        }
      }
    };
  }
  public void start() {
    Bootstrap b = new Bootstrap();
    b.group(nioEventLoopGroup).channel(NioSocketChannel.class).handler(getChannelInitializer());

    try {
      // Start the connection attempt.
      this.channel = b.connect(host, port).sync().channel();
    } catch (InterruptedException e) {
      log.error(e);
    }
  }
 public void connect() throws Exception {
   /*
   mySocket = new Socket(this.host,this.port);
   os = mySocket.getOutputStream();
    */
   group = new NioEventLoopGroup();
   b = new Bootstrap();
   b.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer());
   ch = b.connect(host, port).sync().channel();
   handler = ch.pipeline().get(ClientHandler.class);
   isServerAvaialable = true;
 }
    public ClientChannelManager() {
      Bootstrap bootstrap = new Bootstrap();
      Class<? extends Channel> channelClass = m_descriptor.getChannelClass();

      bootstrap.group(m_descriptor.getGroup()).channel(channelClass);
      bootstrap.handler(new ClientChannelInitializer());

      for (Map.Entry<ChannelOption<Object>, Object> e : m_descriptor.getOptions().entrySet()) {
        bootstrap.option(e.getKey(), e.getValue());
      }

      m_bootstrap = bootstrap;
    }
  protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
      throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap
        .group(workerGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(
            ChannelOption.TCP_NODELAY,
            Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
        .option(
            ChannelOption.SO_REUSEADDR,
            Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
    if (connectTimeout < 1000) {
      bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    } else {
      bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    }
    final NettyClientHandler handler = new NettyClientHandler(this, key);
    bootstrap.handler(
        new ChannelInitializer<SocketChannel>() {

          protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("decoder", new NettyProtocolDecoder());
            pipeline.addLast("encoder", new NettyProtocolEncoder());
            pipeline.addLast("handler", handler);
          }
        });
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync();
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
      LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
      throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
      LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
      throw new Exception(
          "Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
      LOGGER.error(
          "Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
      throw new Exception(
          "Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    NettyClient client = new NettyClient(future, key, connectTimeout);
    handler.setClient(client);
    return client;
  }
  public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioDatagramChannel.class)
          .option(ChannelOption.SO_BROADCAST, true)
          .handler(new QuoteOfTheMomentServerHandler());

      b.bind(PORT).sync().channel().closeFuture().await();
    } finally {
      group.shutdownGracefully();
    }
  }
  /**
   * create connection to remote server
   *
   * @return
   */
  public Channel connect() {
    // Start the connection attempt.
    //	while(true){
    if (channel == null) {
      try {
        // if(flag==1)
        // {
        handler = new MonitorHandler();
        MonitorInitializer mi = new MonitorInitializer(handler, false);

        Bootstrap b = new Bootstrap();
        // @TODO newFixedThreadPool(2);
        b.group(group).channel(NioSocketChannel.class).handler(mi);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make the connection attempt.
        logger.info(host + ";" + port + "IN JobBid monitor");
        channel = b.connect(host, port).syncUninterruptibly();
        channel.awaitUninterruptibly(5000l);
        channel.channel().closeFuture().addListener(new MonitorClosedListener(this));
        // flag=0;
        // Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        if (N == Integer.MAX_VALUE) N = 1;
        else N++;
        // }
        // add listeners waiting to be added
        if (listeners.size() > 0) {
          for (MonitorListener ml : listeners) handler.addListener(ml);
          listeners.clear();
        }
      } catch (Exception ex) {
        logger.debug("failed to initialize the heartbeat connection");
        // logger.error("failed to initialize the heartbeat connection",
        // ex);
      }
    }

    if (channel != null && channel.isDone() && channel.isSuccess()) {

      logger.info("Channel is Created" + channel);
      return channel.channel();
    } else {
      logger.info("In Error from Establish Connection");
      throw new RuntimeException("Not able to establish connection to server");
    }
  }