java.nio.channels.NotYetConnectedException#io.netty.bootstrap.Bootstrap源码实例Demo

下面列出了java.nio.channels.NotYetConnectedException#io.netty.bootstrap.Bootstrap 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: proxy   文件: ProxyClient.java
/**
 * 初始化 连接后端真正服务器
 */
private void initRealServerBoot() {

    //初始化
    realServerBootstrap = new Bootstrap();
    realServerGroup = new NioEventLoopGroup();


    realServerBootstrap.group(realServerGroup);
    realServerBootstrap.channel(NioSocketChannel.class);
    realServerBootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TCPHandler());
            ch.pipeline().addLast(new HttpResponseDecoder());
            ch.pipeline().addLast(new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast(new HttpSendHandler());
        }
    });
}
 
源代码2 项目: archistar-core   文件: OzymandiasClient.java
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Channel connectServer(int port) throws Exception {

    final OzymandiasClientHandler handler = new OzymandiasClientHandler(this);

    Bootstrap b = new Bootstrap();
    b.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addLast(
                            new SslHandler(engine),
                            new ObjectEncoder(),
                            new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)),
                            handler);
                }
            });

    return b.connect("127.0.0.1", port).sync().channel();
}
 
源代码3 项目: Lottor   文件: EchoClient.java
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group) // 注册线程池
                .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
                .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("connected...");
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });
        System.out.println("created..");

        ChannelFuture cf = b.connect().sync(); // 异步连接服务器
        System.out.println("connected..."); // 连接完成

        cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
        System.out.println("closed.."); // 关闭完成
    } finally {
        group.shutdownGracefully().sync(); // 释放线程池资源
    }
}
 
源代码4 项目: netty-4.1.22   文件: EpollSocketTestPermutation.java
@SuppressWarnings("unchecked")
@Override
public List<BootstrapFactory<Bootstrap>> clientSocket() {
    return Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollSocketChannel.class);
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class);
                }
            }
    );
}
 
源代码5 项目: dubbo-remoting-netty4   文件: NettyClient.java
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new Bootstrap();
    // config
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(WORKER_GROUP);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.handler(new ChannelInitializer() {
        public void initChannel(Channel ch) {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline channelPipeline = ch.pipeline();
            channelPipeline.addLast("decoder", adapter.getDecoder());
            channelPipeline.addLast("encoder", adapter.getEncoder());
            channelPipeline.addLast("handler", nettyHandler);
        }
    });

}
 
源代码6 项目: netty4.0.27Learn   文件: EpollSocketChannelTest.java
@Test
public void testTcpInfoReuse() throws Exception {
    EventLoopGroup group = new EpollEventLoopGroup(1);

    try {
        Bootstrap bootstrap = new Bootstrap();
        EpollSocketChannel ch = (EpollSocketChannel) bootstrap.group(group)
                .channel(EpollSocketChannel.class)
                .handler(new ChannelInboundHandlerAdapter())
                .bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        EpollTcpInfo info = new EpollTcpInfo();
        ch.tcpInfo(info);
        assertTcpInfo0(info);
        ch.close().syncUninterruptibly();
    } finally {
        group.shutdownGracefully();
    }
}
 
源代码7 项目: JavaInterview   文件: TimeClient.java
private void connect(String host, int port) throws Exception{
    //配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new TimeClientHandler());
                }
            });

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

    //等待 客户端链路关闭
    cf.channel().closeFuture().sync();
}
 
源代码8 项目: x-pipe   文件: AbstractRedisProxyServerTest.java
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());
    }
 
源代码9 项目: krpc   文件: TCPClient.java
/**
 * 初始化Bootstrap
 * 
 * @return
 */
public static final Bootstrap getBootstrap() {
	EventLoopGroup group = new NioEventLoopGroup();
	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("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
			pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
			pipeline.addLast("decoder", new ByteArrayDecoder());
			pipeline.addLast("encoder", new ByteArrayEncoder());
			pipeline.addLast("handler", new TcpClientHandler());
		}
	});
	return b;
}
 
源代码10 项目: nano-proxy   文件: TrafficSimulationTests.java
@Test
public void simple() throws Exception {
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(new NioEventLoopGroup(1))
			.channel(NioSocketChannel.class)
			.handler(new TrafficGeneratorClientHandler());
	final CountDownLatch latch = new CountDownLatch(1);
	bootstrap.connect("localhost",8010).addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) throws Exception {
			if(future.isSuccess()){
				future.channel().writeAndFlush(Unpooled.buffer().capacity(256).writeZero(256));
			}else {
				System.err.println("Connection attempt failed");
				future.cause().printStackTrace();
			}
			latch.countDown();
		}
	});

latch.await();

}
 
源代码11 项目: netty-4.1.22   文件: RxtxClient.java
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
源代码12 项目: datacollector   文件: TestTCPServerSource.java
private ChannelFuture startTcpClient(
    TCPServerSourceConfig configBean,
    EventLoopGroup workerGroup,
    byte[] data,
    boolean randomlySlice
) throws
    InterruptedException {
  ChannelFuture channelFuture;
  Bootstrap bootstrap = new Bootstrap();
  bootstrap.group(workerGroup);
  bootstrap.channel(NioSocketChannel.class);
  bootstrap.remoteAddress(new InetSocketAddress("localhost", Integer.parseInt(configBean.ports.get(0))));
  bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
  bootstrap.handler(new ChannelInitializer() {
    @Override
    protected void initChannel(Channel ch) throws Exception {
      ch.pipeline().addLast(new TCPServerSourceClientHandler(randomlySlice, data));
    }
  });

  // Start the client.
  channelFuture = bootstrap.connect().sync();

  return channelFuture;
}
 
源代码13 项目: netty-4.1.22   文件: StompClient.java
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new StompSubframeDecoder());
                pipeline.addLast("encoder", new StompSubframeEncoder());
                pipeline.addLast("aggregator", new StompSubframeAggregator(1048576));
                pipeline.addLast("handler", new StompClientHandler());
            }
        });

        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
源代码14 项目: Nukkit   文件: UDPServerSocket.java
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
            bootstrap = new Bootstrap()
                    .channel(EPOLL ? EpollDatagramChannel.class : NioDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(this)
                    .group(EPOLL ? new EpollEventLoopGroup() : new NioEventLoopGroup());
            this.logger.info("Epoll Status is " + EPOLL);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
源代码15 项目: nuls-v2   文件: NettyClient.java
public NettyClient(Node node) {
    this.node = node;
    boot = new Bootstrap();

    AttributeKey<Node> key = null;
    synchronized (NettyClient.class) {
        if (AttributeKey.exists("node")) {
            key = AttributeKey.valueOf("node");
        } else {
            key = AttributeKey.newInstance("node");
        }
    }
    boot.attr(key, node);
    boot.group(worker)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.SO_SNDBUF, 128 * 1024)
            .option(ChannelOption.SO_RCVBUF, 128 * 1024)
            .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNETCI_TIME_OUT)
            .handler(new NulsChannelInitializer<>(new ClientChannelHandler()));
}
 
源代码16 项目: netty4.0.27Learn   文件: ByteEchoPeerBase.java
public void run() throws Exception {
    final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
            connectFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(connectGroup)
                .channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
                .handler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    protected void initChannel(UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new LoggingHandler(LogLevel.INFO),
                                new ByteEchoPeerHandler(messageSize));
                    }
                });
        final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync();
        future.channel().closeFuture().sync();
    } finally {
        connectGroup.shutdownGracefully();
    }
}
 
源代码17 项目: netty-4.1.22   文件: SocketCloseForciblyTest.java
public void testCloseForcibly(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    sb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            SocketChannel childChannel = (SocketChannel) msg;
            childChannel.config().setSoLinger(0);
            childChannel.unsafe().closeForcibly();
        }
    }).childHandler(new ChannelInboundHandlerAdapter());

    cb.handler(new ChannelInboundHandlerAdapter());

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

    cb.connect(sc.localAddress()).channel().closeFuture().syncUninterruptibly();
    sc.close().sync();
}
 
源代码18 项目: nano-proxy   文件: ProxyFrontendHandler.java
@Override
public void channelActive(ChannelHandlerContext ctx) {
	final Channel inboundChannel = ctx.channel();
	// Start the connection attempt.
	Bootstrap b = new Bootstrap();
	b.group(inboundChannel.eventLoop())
			.channel(ctx.channel().getClass())
			.handler(new ProxyBackendHandler(inboundChannel, proxyDefinition))
			.option(ChannelOption.AUTO_READ, false);
	ChannelFuture f = b.connect(proxyDefinition.getRemoteHost(), proxyDefinition.getRemotePort());
	outboundChannel = f.channel();
	f.addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) {
			if (future.isSuccess()) {
				// connection complete start to read first data
				inboundChannel.read();
			} else {
				// Close the connection if the connection attempt has failed.
				inboundChannel.close();
			}
		}
	});
}
 
源代码19 项目: dfactor   文件: DFSocketManager.java
protected ChannelFuture doTcpConntecSync(DFTcpClientCfg cfg, EventLoopGroup ioGroup, ChannelHandler handler){
	if(ioGroup == null){
		return null;
	}
	Bootstrap boot = new Bootstrap();
	boot.group(ioGroup)
		.option(ChannelOption.ALLOCATOR, 
				PooledByteBufAllocator.DEFAULT)
		.option(ChannelOption.SO_KEEPALIVE, cfg.isKeepAlive())
		.option(ChannelOption.SO_RCVBUF, cfg.getSoRecvBufLen())
		.option(ChannelOption.SO_SNDBUF, cfg.getSoSendBufLen())
		.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int)cfg.getConnTimeout())
		.option(ChannelOption.TCP_NODELAY, cfg.isTcpNoDelay())
		.handler(new TcpHandlerInit(false, cfg.getTcpProtocol(), 
				cfg.getTcpMsgMaxLength(), 0, 0, cfg.getWsUri(), null, 
				cfg.getDecoder(), cfg.getEncoder(), cfg.getUserHandler(), cfg.getSslCfg()
				, cfg.getReqData(), handler));
	if(ioGroup instanceof EpollEventLoopGroup){
		boot.channel(EpollSocketChannel.class);
	}else{
		boot.channel(NioSocketChannel.class);
	}
	ChannelFuture future = boot.connect(cfg.host, cfg.port);
	return future;
}
 
源代码20 项目: krpc   文件: CatNettyClient.java
public void init() {

        timer = new Timer("krpc_cat_netty_timer");

        workerGroup = new NioEventLoopGroup(workerThreads, workThreadFactory);

        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("handler", CatNettyClient.this);
            }
        });
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        // bootstrap.option(ChannelOption.SO_RCVBUF, 65536);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);

        log.info("cat netty client started");
    }
 
源代码21 项目: netty-learning   文件: TimeClient.java
public static void main(String[] args) throws InterruptedException {
    String host = "127.0.0.1" ;
    int port = 11211 ;

    EventLoopGroup group = new NioEventLoopGroup() ;

    try {
        Bootstrap bootstrap = new Bootstrap() ;
        bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.SO_KEEPALIVE,true)
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new TimeClientHandler()) ;
            }
        });

        // 启动客户端
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();

        // 等待连接关闭
        channelFuture.channel().closeFuture().sync() ;

    }finally {
        group.shutdownGracefully();
    }
}
 
源代码22 项目: aws-sdk-java-v2   文件: BootstrapProvider.java
/**
 * Creates a Bootstrap for a specific host and port with an unresolved InetSocketAddress as the remoteAddress.
 * @param host The unresolved remote hostname
 * @param port The remote port
 * @return A newly created Bootstrap using the configuration this provider was initialized with, and having an
 * unresolved remote address.
 */
public Bootstrap createBootstrap(String host, int port) {
    Bootstrap bootstrap =
        new Bootstrap()
            .group(sdkEventLoopGroup.eventLoopGroup())
            .channelFactory(sdkEventLoopGroup.channelFactory())
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyConfiguration.connectTimeoutMillis())
            .remoteAddress(InetSocketAddress.createUnresolved(host, port));
    sdkChannelOptions.channelOptions().forEach(bootstrap::option);

    return bootstrap;
}
 
源代码23 项目: riiablo   文件: TestClient.java
@Override
  public void create() {
    Gdx.app.setLogLevel(Application.LOG_DEBUG);

    group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap()
          .group(group)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.SO_KEEPALIVE, true)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
              UnicastEndpoint<ByteBuf> endpoint = new TcpEndpoint(ch, TestClient.this);
              TestClient.this.endpoint = endpoint;
              ch.pipeline()
                  .addLast(new EndpointedChannelHandler<>(ByteBuf.class, endpoint))
              ;
            }
          });

      ChannelFuture f = b.connect("localhost", Main.PORT).sync();
      sendConnectionPacket();
//      sendConnectionPacket();
//      sendDisconnectPacket();
    } catch (Throwable t) {
      Gdx.app.error(TAG, t.getMessage(), t);
      Gdx.app.exit();
    }
  }
 
源代码24 项目: panama   文件: AbstractClient.java
@Override
    public Client connect(InetSocketAddress inetSocketAddress) {
        if (!close) {
            return this;
        }

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workGroup).
                channel(NioSocketChannel.class).
                handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        setupPipeline(ch.pipeline());
                    }
                });
        try {
            close = false;
            connectFuture = bootstrap.connect(inetSocketAddress).sync();
            connectFuture.addListener((future) -> {
//                System.out.println("operationComplete");
            });
        } catch (Exception e) {
            e.printStackTrace();
            close = true;
            return null;
        }

        return this;
    }
 
源代码25 项目: archistar-core   文件: ServerServerCommunication.java
/**
 * connects to all replicas
 *
 * @throws InterruptedException
 */
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public void connect() throws InterruptedException {
    for (Entry<Integer, Integer> e : this.serverList.entrySet()) {
        int replicaId = e.getKey();
        int replicaPort = e.getValue();

        if (replicaId != myServerId) {
            Bootstrap b = new Bootstrap();
            b.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // enable SSL/TLS support
                            SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                            engine.setUseClientMode(true);

                            ch.pipeline().addLast(
                                    new SslHandler(engine),
                                    new ObjectEncoder(),
                                    new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)));
                        }
                    });

            /* wait till server is connected */
            ChannelFuture f = null;
            do {
                f = b.connect("127.0.0.1", replicaPort);
                f.await();
            } while (!(f.isDone() && f.isSuccess()));

            this.channels.add(f.sync().channel());
        }
    }
}
 
源代码26 项目: netty-cookbook   文件: BootstrapTemplate.java
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
源代码27 项目: qpid-jms   文件: NettyTcpTransport.java
private void configureNetty(Bootstrap bootstrap, TransportOptions options) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());

    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }

    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }

    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }

    if (options.getLocalAddress() != null || options.getLocalPort() != 0) {
        if(options.getLocalAddress() != null) {
            bootstrap.localAddress(options.getLocalAddress(), options.getLocalPort());
        } else {
            bootstrap.localAddress(options.getLocalPort());
        }
    }
    if (options.getProxyHandlerSupplier() != null) {
        // in case we have a proxy we do not want to resolve the address by ourselves but leave this to the proxy
        bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
}
 
源代码28 项目: kryonetty   文件: Client.java
/**
 * Create a new client connected to the given socket.
 * @param serverAddress Server to connect to.
 */
public Client() {
	group = new NioEventLoopGroup();
	
	bootstrap = new Bootstrap();
	bootstrap.group(group)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new KryonettyClientInitializer(this));
}
 
源代码29 项目: nomulus   文件: ProbingActionTest.java
@Test
public void testSuccess_newChannel() throws Exception {
  // setup

  LocalAddress address = new LocalAddress(ADDRESS_NAME);
  Bootstrap bootstrap =
      new Bootstrap().group(nettyRule.getEventLoopGroup()).channel(LocalChannel.class);

  // Sets up a Protocol corresponding to when a new connection is created.
  Protocol protocol =
      Protocol.builder()
          .setHandlerProviders(ImmutableList.of(() -> conversionHandler, () -> testHandler))
          .setName(PROTOCOL_NAME)
          .setPort(TEST_PORT)
          .setPersistentConnection(false)
          .build();

  nettyRule.setUpServer(address);

  // Sets up a ProbingAction with existing channel using test specified attributes.
  ProbingAction action =
      ProbingAction.builder()
          .setBootstrap(bootstrap)
          .setProtocol(protocol)
          .setDelay(Duration.ZERO)
          .setOutboundMessage(new TestMessage(TEST_MESSAGE))
          .setHost(ADDRESS_NAME)
          .build();

  // tests main function of ProbingAction
  ChannelFuture future = action.call();

  // Tests to see if message is properly sent to remote server
  nettyRule.assertReceivedMessage(TEST_MESSAGE);

  future = future.syncUninterruptibly();
  // Tests to see that, since server responds, we have set future to true
  assertThat(future.isSuccess()).isTrue();
  assertThat(((TestActionHandler) testHandler).getResponse().toString()).isEqualTo(TEST_MESSAGE);
}
 
源代码30 项目: netty-4.1.22   文件: ObjectEchoClient.java
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

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

        // Start the connection attempt.
        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}