Пример #1
0
  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());
          }
        });
  }
Пример #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();
    }
  }
Пример #3
0
  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();
  }
Пример #4
0
  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();
    }
  }
Пример #5
0
  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 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();
    }
  }
Пример #7
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();
    }
  }
Пример #8
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();
    }
  }
Пример #9
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();
    }
  }
Пример #10
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("重连成功");
    }
  }
Пример #11
0
  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());
    }
  }
Пример #12
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();
   }
 }
Пример #13
0
  @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();
            }
          }
        });
  }
Пример #14
0
  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();
    }
  }
Пример #15
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();
   }
 }
Пример #16
0
  /** 初始化 */
  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初始化完成");
  }
Пример #17
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();
    }
  }
Пример #18
0
    public Channel getActiveChannel() throws InterruptedException {
      List<InetSocketAddress> addresses = m_descriptor.getRemoteAddresses();

      if (!addresses.equals(m_addresses)) { // first time or addresses changed
        m_addresses = addresses;

        for (int i = 0; i < addresses.size(); i++) {
          InetSocketAddress address = addresses.get(i);
          ChannelFuture future = m_bootstrap.connect(address).sync();

          if (future.isSuccess()) {
            // close old channel
            if (m_channel != null) {
              m_channel.close();
            }

            // m_logger.info(String.format("Connected to %s server(%s:%s)", m_descriptor.getName(),
            // address.getHostName(), address.getPort()));
            m_channel = future.channel();
            m_index = i;
            break;
          }
        }

        return m_channel;
      } else {
        // closed by peer
        if (m_channel != null && m_channel.closeFuture().isSuccess()) {
          // TODO
        }

        // try to recover connection to primary server
        if (m_index > 0) {
          if (m_primary == null) {
            long now = System.currentTimeMillis();

            if (m_lastCheckTime + m_failBackCheckInternal < now) {
              InetSocketAddress address = m_addresses.get(m_index);

              m_lastCheckTime = now;
              m_primary = m_bootstrap.connect(address);
            }
          } else {
            Channel channel = m_primary.channel();

            if (channel.isOpen() && channel.isActive()) {
              m_channel = channel;
              m_index = 0;
            }
          }
        }

        if (m_channel != null && m_channel.isOpen() && m_channel.isActive()) {
          return m_channel;
        } else {
          return null;
        }
      }
    }
 public void testConnectTimeout(Bootstrap cb) throws Throwable {
   cb.handler(new TestHandler()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
   ChannelFuture future = cb.connect(BAD_HOST, BAD_PORT);
   try {
     assertThat(future.await(3000), is(true));
   } finally {
     future.channel().close();
   }
 }
  @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();
            }
          }
        });
  }
Пример #21
0
  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();
    }
  }
Пример #22
0
  @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);
          }
        }
      }
    };
  }
Пример #23
0
  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");
    }
  }
Пример #24
0
  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);
    }
  }
Пример #25
0
 public static ChannelFuture connect(PeerAddress peerAddress, byte[] hashinfo)
     throws InterruptedException {
   if (bootstrap == null) {
     init();
   }
   bootstrap.handler(HandlerFactory.client(hashinfo));
   ChannelFuture channelFuture =
       bootstrap.connect(peerAddress.getAddress(), peerAddress.getPort()).sync();
   register(peerAddress, channelFuture.channel());
   return channelFuture;
 }
  public void testSslRenegotiationRejected(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    reset();

    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          @SuppressWarnings("deprecation")
          public void initChannel(Channel sch) throws Exception {
            serverChannel = sch;
            serverSslHandler = serverCtx.newHandler(sch.alloc());

            sch.pipeline().addLast("ssl", serverSslHandler);
            sch.pipeline().addLast("handler", serverHandler);
          }
        });

    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          @SuppressWarnings("deprecation")
          public void initChannel(Channel sch) throws Exception {
            clientChannel = sch;
            clientSslHandler = clientCtx.newHandler(sch.alloc());

            sch.pipeline().addLast("ssl", clientSslHandler);
            sch.pipeline().addLast("handler", clientHandler);
          }
        });

    Channel sc = sb.bind().sync().channel();
    cb.connect().sync();

    Future<Channel> clientHandshakeFuture = clientSslHandler.handshakeFuture();
    clientHandshakeFuture.sync();

    String renegotiation = "SSL_RSA_WITH_RC4_128_SHA";
    clientSslHandler.engine().setEnabledCipherSuites(new String[] {renegotiation});
    clientSslHandler.renegotiate().await();
    serverChannel.close().awaitUninterruptibly();
    clientChannel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();
    try {
      if (serverException.get() != null) {
        throw serverException.get();
      }
      fail();
    } catch (DecoderException e) {
      assertTrue(e.getCause() instanceof SSLHandshakeException);
    }
    if (clientException.get() != null) {
      throw clientException.get();
    }
  }
 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;
 }
Пример #28
0
    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;
    }
Пример #29
0
  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();
    }
  }
Пример #30
0
  private void setChannelFactory(final Bootstrap bootstrap, final KeyMapping keys) {
    if (keys != null && !keys.isEmpty()) {
      if (this.cf == null) {
        throw new UnsupportedOperationException(
            "No key access instance available, cannot use key mapping");
      }

      LOG.debug("Adding MD5 keys {} to boostrap {}", keys, bootstrap);
      bootstrap.channelFactory(this.cf);
      bootstrap.option(MD5ChannelOption.TCP_MD5SIG, keys);
    } else {
      bootstrap.channel(NioSocketChannel.class);
    }
  }