Java Code Examples for io.netty.bootstrap.Bootstrap#connect()

The following examples show how to use io.netty.bootstrap.Bootstrap#connect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NettyThreadManager.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
/**
 * 异步建立连接localHost
 *
 * @param hostAndPort      服务器地址
 * @param sndBuffer        socket发送缓冲区
 * @param rcvBuffer        socket接收缓冲区
 * @param connectTimeoutMs 建立连接超时时间
 * @param initializer      channel初始化类,根据使用的协议(eg:tcp,ws) 和 序列化方式(eg:json,protoBuf)确定
 * @return channelFuture 注意使用{@link ChannelFuture#sync()} 会抛出异常。
 * 使用{@link ChannelFuture#await()} 和{@link ChannelFuture#isSuccess()} 安全处理。
 * 此外,使用channel 需要调用 {@link Channel#isActive()}检查是否成功和远程建立连接
 */
public ChannelFuture connectAsyn(HostAndPort hostAndPort, int sndBuffer, int rcvBuffer, int connectTimeoutMs,
                                 ChannelInitializer<SocketChannel> initializer) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);

    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(initializer);

    bootstrap.option(ChannelOption.SO_KEEPALIVE, false);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_SNDBUF, sndBuffer);
    bootstrap.option(ChannelOption.SO_RCVBUF, rcvBuffer);
    bootstrap.option(ChannelOption.SO_LINGER, 0);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, WRITE_BUFFER_WATER_MARK);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs);
    return bootstrap.connect(hostAndPort.getHost(), hostAndPort.getPort());
}
 
Example 2
Source File: ChannelMediator.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Establishing TCP connection to server
 *
 * @param remoteAddress remote address
 * */
public ChannelFuture connectToServer(final InetSocketAddress remoteAddress) {
  if (remoteAddress == null) {
    throw new IllegalStateException("remote address is null");
  }
  Bootstrap bootstrap = new Bootstrap().group(_upstreamWorkerGroup);
  bootstrap.channelFactory(NioSocketChannel::new);
  ServerChannelHandler serverChannelHandler = new ServerChannelHandler(this);

  bootstrap.handler(new ChannelInitializer<Channel>() {
    protected void initChannel(Channel ch)
        throws Exception {
      initChannelPipeline(ch.pipeline(), serverChannelHandler, _serverConnectionIdleTimeoutMsec);
      _serverChannel = ch;
    }
  });
  LOG.debug("Server channel is ready. About to connect....");
  return bootstrap.connect(remoteAddress);
}
 
Example 3
Source File: AbstractRedisProxyServerTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
public ChannelFuture connect() throws Exception {

        startServer();
        Bootstrap b = new Bootstrap();
        b.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                });
        return b.connect("127.0.0.1", config.frontendTcpPort());
    }
 
Example 4
Source File: DatagramConnectNotExistsTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void testConnectNotExists(Bootstrap cb) throws Throwable {
    final Promise<Throwable> promise = ImmediateEventExecutor.INSTANCE.newPromise();
    cb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            promise.trySuccess(cause);
        }
    });
    ChannelFuture future = cb.connect(NetUtil.LOCALHOST, SocketTestPermutation.BAD_PORT);
    try {
        Channel datagramChannel = future.syncUninterruptibly().channel();
        Assert.assertTrue(datagramChannel.isActive());
        datagramChannel.writeAndFlush(
                Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII)).syncUninterruptibly();
        if (!(datagramChannel instanceof OioDatagramChannel)) {
            Assert.assertTrue(promise.syncUninterruptibly().getNow() instanceof PortUnreachableException);
        }
    } finally {
        future.channel().close();
    }
}
 
Example 5
Source File: NettyClient.java    From spring-boot-demo with MIT License 6 votes vote down vote up
@PostConstruct
public void start() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .remoteAddress(host, port)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new NettyClientInitializer());
    ChannelFuture future = bootstrap.connect();
    //客户端断线重连逻辑
    future.addListener((ChannelFutureListener) future1 -> {
        if (future1.isSuccess()) {
            log.info("连接Netty服务端成功");
        } else {
            log.info("连接失败,进行断线重连");
            future1.channel().eventLoop().schedule(() -> start(), 20, TimeUnit.SECONDS);
        }
    });
    socketChannel = (SocketChannel) future.channel();
}
 
Example 6
Source File: OioEventLoopTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testTooManyClientChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Bootstrap cb = new Bootstrap();
    cb.channel(OioSocketChannel.class);
    cb.group(g);
    cb.handler(new ChannelInboundHandlerAdapter());
    ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    f2.await();

    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));

    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });

    notified.await();
    g.shutdownGracefully();
}
 
Example 7
Source File: NettyPerfClient.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the NettyPerfClient.
 * @throws InterruptedException
 */
protected void start() {
  logger.info("Starting NettyPerfClient");
  reporter.start();
  group = new NioEventLoopGroup(concurrency);
  perfClientStartTime = System.currentTimeMillis();
  for (String host : hosts) {
    logger.info("Connecting to {}:{}", host, port);
    // create a new bootstrap with a fixed remote address for each host. This is the simplest way to support
    // reconnection on failure. All bootstraps will share the same event loop group.
    Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).remoteAddress(host, port);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
      @Override
      public void initChannel(SocketChannel ch) {
        logger.info("Initializing the channel to {}:{}", host, port);
        if (sslFactory != null) {
          ch.pipeline().addLast(new SslHandler(sslFactory.createSSLEngine(host, port, SSLFactory.Mode.CLIENT)));
        }
        ch.pipeline()
            .addLast(new HttpClientCodec())
            .addLast(new ChunkedWriteHandler())
            .addLast(new ResponseHandler(bootstrap));
      }
    });
    for (int i = 0; i < concurrency; i++) {
      ChannelFuture future = bootstrap.connect();
      future.addListener(channelConnectListener);
    }
    hostToRequestCount.put(host, new AtomicLong(0));
    hostToSleepTime.put(host, sleepTimeInMs);
  }
  if (backgroundScheduler != null) {
    backgroundScheduler.scheduleAtFixedRate(updater, 0, 1, TimeUnit.SECONDS);
    logger.info("Background scheduler is instantiated to update sleep time.");
  }
  isRunning = true;
  logger.info("Created {} channel(s) per remote host", concurrency);
  logger.info("NettyPerfClient started");
}
 
Example 8
Source File: SocketConnectionAttemptTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 9
Source File: SocketConnectionAttemptTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 10
Source File: SimpleHttpProxyHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
 
Example 11
Source File: GenericClient.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void connect() {
    Assert.notNull(serverAttr, "serverAttr can not be null");
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new ClientInitializer(GenericClient.this));
                }
            });

    ChannelFuture future = bootstrap.connect(serverAttr.getAddress(), serverAttr.getPort());
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> f) throws Exception {
            channel = future.channel();
            if (f.isSuccess()) {
                connected = true;
                log.info("[{}] Has connected to {} successfully", GenericClient.class.getSimpleName(), serverAttr);
            } else {
                log.warn("[{}] Connect to {} failed, cause={}", GenericClient.class.getSimpleName(), serverAttr, f.cause().getMessage());
                // fire the channelInactive and make sure
                // the {@link HealthyChecker} will reconnect
                channel.pipeline().fireChannelInactive();
            }
        }
    });
}
 
Example 12
Source File: NettyClient.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void start() {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    clientHandler=new ClientHandler();
    b.group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE,true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                    p.addLast("decoder", new StringDecoder(StandardCharsets.UTF_8));
                    p.addLast("encoder", new StringEncoder(Charset.forName("GBK")));
                    p.addLast(new IdleStateHandler(1,0,0,TimeUnit.SECONDS));
                    p.addLast(clientHandler);
                }
            });
    //���ӷ����
    ChannelFuture connect = b.connect(NETTY_SERVER_IP, NETTY_SERVER_PORT);
    //��������
    connect.addListener((ChannelFutureListener) channelFuture -> {
        if (!channelFuture.isSuccess()) {
            final EventLoop loop = channelFuture.channel().eventLoop();
            loop.schedule(() -> {
                try {
                    log.error("��������Ӳ��ϣ���ʼ��������...");
                    start();
                } catch (Exception ignored) {

                }
            }, 1L, TimeUnit.SECONDS);
        } else {
            channel = channelFuture.channel();
            log.info("��������ӳɹ�...");
        }
    });
}
 
Example 13
Source File: HttpProxyClientHandler.java    From http-proxy-netty with MIT License 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (header.isComplete()) {
        remoteChannel.writeAndFlush(msg); // just forward
        return;
    }

    ByteBuf in = (ByteBuf) msg;
    header.digest(in);

    if (!header.isComplete()) {
        in.release();
        return;
    }

    logger.info(id + " {}", header);
    clientChannel.config().setAutoRead(false); // disable AutoRead until remote connection is ready

    if (header.isHttps()) { // if https, respond 200 to create tunnel
        clientChannel.writeAndFlush(Unpooled.wrappedBuffer("HTTP/1.1 200 Connection Established\r\n\r\n".getBytes()));
    }

    Bootstrap b = new Bootstrap();
    b.group(clientChannel.eventLoop()) // use the same EventLoop
            .channel(clientChannel.getClass())
            .handler(appCtx.getBean(HttpProxyRemoteHandler.class, id, clientChannel));
    ChannelFuture f = b.connect(header.getHost(), header.getPort());
    remoteChannel = f.channel();

    f.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            clientChannel.config().setAutoRead(true); // connection is ready, enable AutoRead
            if (!header.isHttps()) { // forward header and remaining bytes
                remoteChannel.write(header.getByteBuf());
            }
            remoteChannel.writeAndFlush(in);
        } else {
            in.release();
            clientChannel.close();
        }
    });
}
 
Example 14
Source File: JNettyDomainConnector.java    From Jupiter with Apache License 2.0 4 votes vote down vote up
@Override
public JConnection connect(UnresolvedAddress address, boolean async) {
    setOptions();

    final Bootstrap boot = bootstrap();
    final SocketAddress socketAddress = new DomainSocketAddress(address.getPath());
    final JChannelGroup group = group(address);

    // 重连watchdog
    final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, socketAddress, group) {

        @Override
        public ChannelHandler[] handlers() {
            return new ChannelHandler[] {
                    new FlushConsolidationHandler(JConstants.EXPLICIT_FLUSH_AFTER_FLUSHES, true),
                    this,
                    new IdleStateChecker(timer, 0, JConstants.WRITER_IDLE_TIME_SECONDS, 0),
                    idleStateTrigger,
                    CodecConfig.isCodecLowCopy() ? new LowCopyProtocolDecoder() : new ProtocolDecoder(),
                    encoder,
                    handler
            };
        }
    };

    ChannelFuture future;
    try {
        synchronized (bootstrapLock()) {
            boot.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(socketAddress);
        }

        // 以下代码在synchronized同步块外面是安全的
        if (!async) {
            future.sync();
        }
    } catch (Throwable t) {
        throw new ConnectFailedException("Connects to [" + address + "] fails", t);
    }

    return new JNettyConnection(address, future) {

        @Override
        public void setReconnect(boolean reconnect) {
            if (reconnect) {
                watchdog.start();
            } else {
                watchdog.stop();
            }
        }
    };
}
 
Example 15
Source File: ProxyServer.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/**
 * Establishes an outbound relay channel and sets the relevant metadata on both channels.
 *
 * <p>This method also adds a listener that is called when the established outbound connection
 * is closed. The outbound connection to GAE is *not* guaranteed to persist. In case that the
 * outbound connection closes but the inbound connection is still active, the listener calls
 * this function again to re-establish another outbound connection. The metadata is also reset
 * so that the inbound channel knows to relay to the new outbound channel.
 */
private static void connectOutboundChannel(
    Bootstrap bootstrap,
    FrontendProtocol inboundProtocol,
    BackendProtocol outboundProtocol,
    NioSocketChannel inboundChannel) {
  ChannelFuture outboundChannelFuture =
      bootstrap.connect(outboundProtocol.host(), outboundProtocol.port());
  outboundChannelFuture.addListener(
      (ChannelFuture future) -> {
        if (future.isSuccess()) {
          // Outbound connection is successful, now we can set the metadata to couple these two
          // connections together.
          Channel outboundChannel = future.channel();
          // Inbound channel relays to outbound channel.
          inboundChannel.attr(RELAY_CHANNEL_KEY).set(outboundChannel);
          // Outbound channel established successfully, inbound channel can start reading.
          // This setter also calls channel.read() to request read operation.
          inboundChannel.config().setAutoRead(true);
          logger.atInfo().log(
              "Relay established: %s <-> %s\nFRONTEND: %s\nBACKEND: %s",
              inboundProtocol.name(), outboundProtocol.name(), inboundChannel, outboundChannel);
          // Now that we have a functional relay channel to the backend, if there's any
          // buffered requests, send them off to the relay channel. We need to obtain a copy
          // of the messages and clear the queue first, because if the relay is not successful,
          // the message will be written back to the queue, causing an infinite loop.
          Queue<Object> relayBuffer = inboundChannel.attr(RELAY_BUFFER_KEY).get();
          Object[] messages = relayBuffer.toArray();
          relayBuffer.clear();
          for (Object msg : messages) {
            logger.atInfo().log(
                "Relay retried: %s <-> %s\nFRONTEND: %s\nBACKEND: %s\nHASH: %s",
                inboundProtocol.name(),
                outboundProtocol.name(),
                inboundChannel,
                outboundChannel,
                msg.hashCode());
            writeToRelayChannel(inboundChannel, outboundChannel, msg, true);
          }
          // When this outbound connection is closed, try reconnecting if the inbound connection
          // is still active.
          ChannelFuture unusedChannelFuture =
              outboundChannel
                  .closeFuture()
                  .addListener(
                      (ChannelFuture future2) -> {
                        if (inboundChannel.isActive()) {
                          logger.atInfo().log(
                              "Relay interrupted: %s <-> %s\nFRONTEND: %s\nBACKEND: %s",
                              inboundProtocol.name(),
                              outboundProtocol.name(),
                              inboundChannel,
                              outboundChannel);
                          connectOutboundChannel(
                              bootstrap, inboundProtocol, outboundProtocol, inboundChannel);
                        } else {
                          logger.atInfo().log(
                              "Relay terminated: %s <-> %s\nFRONTEND: %s\nBACKEND: %s",
                              inboundProtocol.name(),
                              outboundProtocol.name(),
                              inboundChannel,
                              outboundChannel);
                        }
                      });
        } else {
          // We cannot connect to GAE for unknown reasons, no relay can be done so drop the
          // inbound connection as well.
          logger.atSevere().withCause(future.cause()).log(
              "Cannot connect to relay channel for %s channel: %s.",
              inboundProtocol.name(), inboundChannel);
          ChannelFuture unusedFuture = inboundChannel.close();
        }
      });
}
 
Example 16
Source File: NioUdtMessageRendezvousChannelTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * verify basic echo message rendezvous
 *
 * FIXME: Re-enable after making it pass on Windows without unncessary tight loop.
 *        https://github.com/netty/netty/issues/2853
 */
@Test(timeout = 10 * 1000)
@Ignore
public void basicEcho() throws Exception {

    final int messageSize = 64 * 1024;
    final int transferLimit = messageSize * 16;

    final Meter rate1 = Metrics.newMeter(
            NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);

    final Meter rate2 = Metrics.newMeter(
            NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);

    final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
    final InetSocketAddress addr2 = UnitHelp.localSocketAddress();

    final EchoMessageHandler handler1 = new EchoMessageHandler(rate1, messageSize);
    final EchoMessageHandler handler2 = new EchoMessageHandler(rate2, messageSize);

    final NioEventLoopGroup group1 = new NioEventLoopGroup(
            1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup group2 = new NioEventLoopGroup(
            1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);

    final Bootstrap boot1 = new Bootstrap();
    boot1.group(group1)
         .channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
         .localAddress(addr1).remoteAddress(addr2).handler(handler1);

    final Bootstrap boot2 = new Bootstrap();
    boot2.group(group2)
         .channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
         .localAddress(addr2).remoteAddress(addr1).handler(handler2);

    final ChannelFuture connectFuture1 = boot1.connect();
    final ChannelFuture connectFuture2 = boot2.connect();

    while (handler1.meter().count() < transferLimit
            && handler2.meter().count() < transferLimit) {

        log.info("progress : {} {}", handler1.meter().count(), handler2
                .meter().count());

        Thread.sleep(1000);
    }

    connectFuture1.channel().close().sync();
    connectFuture2.channel().close().sync();

    log.info("handler1 : {}", handler1.meter().count());
    log.info("handler2 : {}", handler2.meter().count());

    assertTrue(handler1.meter().count() >= transferLimit);
    assertTrue(handler2.meter().count() >= transferLimit);

    assertEquals(handler1.meter().count(), handler2.meter().count());

    group1.shutdownGracefully();
    group2.shutdownGracefully();

    group1.terminationFuture().sync();
    group2.terminationFuture().sync();
}
 
Example 17
Source File: NioUdtByteRendezvousChannelTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * verify basic echo byte rendezvous
 */
@Test(timeout = 10 * 1000)
public void basicEcho() throws Exception {

    final int messageSize = 64 * 1024;
    final int transferLimit = messageSize * 16;

    final Meter rate1 = Metrics.newMeter(
            NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes",
            TimeUnit.SECONDS);

    final Meter rate2 = Metrics.newMeter(
            NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes",
            TimeUnit.SECONDS);

    final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
    final InetSocketAddress addr2 = UnitHelp.localSocketAddress();

    final EchoByteHandler handler1 = new EchoByteHandler(rate1, messageSize);
    final EchoByteHandler handler2 = new EchoByteHandler(rate2, messageSize);

    final NioEventLoopGroup group1 = new NioEventLoopGroup(
            1, Executors.defaultThreadFactory(), NioUdtProvider.BYTE_PROVIDER);
    final NioEventLoopGroup group2 = new NioEventLoopGroup(
            1, Executors.defaultThreadFactory(), NioUdtProvider.BYTE_PROVIDER);

    final Bootstrap boot1 = new Bootstrap();
    boot1.group(group1)
         .channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
         .localAddress(addr1)
         .remoteAddress(addr2)
         .handler(handler1);

    final Bootstrap boot2 = new Bootstrap();
    boot2.group(group1)
         .channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
         .localAddress(addr2)
         .remoteAddress(addr1)
         .handler(handler2);

    final ChannelFuture connectFuture1 = boot1.connect();
    final ChannelFuture connectFuture2 = boot2.connect();

    while (handler1.meter().count() < transferLimit
            && handler2.meter().count() < transferLimit) {

        log.info("progress : {} {}", handler1.meter().count(), handler2
                .meter().count());

        Thread.sleep(1000);
    }

    connectFuture1.channel().close().sync();
    connectFuture2.channel().close().sync();

    log.info("handler1 : {}", handler1.meter().count());
    log.info("handler2 : {}", handler2.meter().count());

    assertTrue(handler1.meter().count() >= transferLimit);
    assertTrue(handler2.meter().count() >= transferLimit);

    assertEquals(handler1.meter().count(), handler2.meter().count());

    group1.shutdownGracefully();
    group2.shutdownGracefully();

    group1.terminationFuture().sync();
    group2.terminationFuture().sync();
}
 
Example 18
Source File: JNettyTcpConnector.java    From Jupiter with Apache License 2.0 4 votes vote down vote up
@Override
public JConnection connect(UnresolvedAddress address, boolean async) {
    setOptions();

    final Bootstrap boot = bootstrap();
    final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort());
    final JChannelGroup group = group(address);

    // 重连watchdog
    final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, socketAddress, group) {

        @Override
        public ChannelHandler[] handlers() {
            return new ChannelHandler[] {
                    new FlushConsolidationHandler(JConstants.EXPLICIT_FLUSH_AFTER_FLUSHES, true),
                    this,
                    new IdleStateChecker(timer, 0, JConstants.WRITER_IDLE_TIME_SECONDS, 0),
                    idleStateTrigger,
                    CodecConfig.isCodecLowCopy() ? new LowCopyProtocolDecoder() : new ProtocolDecoder(),
                    encoder,
                    handler
            };
        }
    };

    ChannelFuture future;
    try {
        synchronized (bootstrapLock()) {
            boot.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(socketAddress);
        }

        // 以下代码在synchronized同步块外面是安全的
        if (!async) {
            future.sync();
        }
    } catch (Throwable t) {
        throw new ConnectFailedException("Connects to [" + address + "] fails", t);
    }

    return new JNettyConnection(address, future) {

        @Override
        public void setReconnect(boolean reconnect) {
            if (reconnect) {
                watchdog.start();
            } else {
                watchdog.stop();
            }
        }
    };
}
 
Example 19
Source File: EchoClientController.java    From examples-javafx-repos1 with Apache License 2.0 4 votes vote down vote up
@FXML
public void connect() {
	
	if( connected.get() ) {
		if( logger.isWarnEnabled() ) {
			logger.warn("client already connected; skipping connect");
		}
		return;  // already connected; should be prevented with disabled
	}
	
	String host = tfHost.getText();
	int port = Integer.parseInt(tfPort.getText());

	group = new NioEventLoopGroup();
	
	Task<Channel> task = new Task<Channel>() {

		@Override
		protected Channel call() throws Exception {
			
			updateMessage("Bootstrapping");
			updateProgress(0.1d, 1.0d);
			
			Bootstrap b = new Bootstrap();
			b
				.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress( new InetSocketAddress(host, port) )
				.handler( new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new EchoClientHandler(receivingMessageModel));
					}
				});
			
			ChannelFuture f = b.connect();
			Channel chn = f.channel();
			
			updateMessage("Connecting");
			updateProgress(0.2d, 1.0d);

			f.sync();

			return chn;
		}

		@Override
		protected void succeeded() {
			
			channel = getValue();
			connected.set(true);
		}

		@Override
		protected void failed() {
			
			Throwable exc = getException();
			logger.error( "client connect error", exc );
			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("Client");
			alert.setHeaderText( exc.getClass().getName() );
			alert.setContentText( exc.getMessage() );
			alert.showAndWait();
			
			connected.set(false);
		}
	};
	
	hboxStatus.visibleProperty().bind( task.runningProperty() );
	lblStatus.textProperty().bind( task.messageProperty() );
	piStatus.progressProperty().bind(task.progressProperty());
	
	new Thread(task).start();
}
 
Example 20
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 2 votes vote down vote up
/**
 * Bootstrap a new {@link Channel}. The default implementation uses {@link Bootstrap#connect()}, sub-classes may
 * override this.
 * <p>
 * The {@link Bootstrap} that is passed in here is cloned via {@link Bootstrap#clone()}, so it is safe to modify.
 * 引导一个新的通道。默认实现使用Bootstrap.connect(),子类可能会覆盖这个。
 这里传递的引导程序是通过Bootstrap.clone()克隆的,因此修改是安全的。
 */
protected ChannelFuture connectChannel(Bootstrap bs) {
    return bs.connect();
}