Java Code Examples for io.netty.bootstrap.Bootstrap

The following examples show how to use io.netty.bootstrap.Bootstrap. These examples are extracted from open source projects. 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 Project: proxy   Source File: ProxyClient.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化 连接后端真正服务器
 */
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());
        }
    });
}
 
Example 2
@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();
}
 
Example 3
Source Project: Lottor   Source File: EchoClient.java    License: MIT License 6 votes vote down vote up
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(); // 释放线程池资源
    }
}
 
Example 4
Source Project: netty-4.1.22   Source File: EpollSocketTestPermutation.java    License: Apache License 2.0 6 votes vote down vote up
@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);
                }
            }
    );
}
 
Example 5
Source Project: dubbo-remoting-netty4   Source File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@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);
        }
    });

}
 
Example 6
Source Project: netty4.0.27Learn   Source File: EpollSocketChannelTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 7
Source Project: JavaInterview   Source File: TimeClient.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 8
Source Project: x-pipe   Source File: AbstractRedisProxyServerTest.java    License: 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 9
Source Project: krpc   Source File: TCPClient.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化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;
}
 
Example 10
Source Project: nano-proxy   Source File: TrafficSimulationTests.java    License: Apache License 2.0 6 votes vote down vote up
@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();

}
 
Example 11
Source Project: netty-4.1.22   Source File: RxtxClient.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 12
Source Project: datacollector   Source File: TestTCPServerSource.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 13
Source Project: netty-4.1.22   Source File: StompClient.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 14
Source Project: Nukkit   Source File: UDPServerSocket.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example 15
Source Project: nuls-v2   Source File: NettyClient.java    License: MIT License 6 votes vote down vote up
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()));
}
 
Example 16
Source Project: netty4.0.27Learn   Source File: ByteEchoPeerBase.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 17
Source Project: netty-4.1.22   Source File: SocketCloseForciblyTest.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 18
Source Project: nano-proxy   Source File: ProxyFrontendHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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();
			}
		}
	});
}
 
Example 19
Source Project: dfactor   Source File: DFSocketManager.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 20
Source Project: krpc   Source File: CatNettyClient.java    License: Apache License 2.0 6 votes vote down vote up
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");
    }
 
Example 21
Source Project: netty-learning   Source File: TimeClient.java    License: MIT License 5 votes vote down vote up
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();
    }
}
 
Example 22
Source Project: aws-sdk-java-v2   Source File: BootstrapProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 23
Source Project: riiablo   Source File: TestClient.java    License: Apache License 2.0 5 votes vote down vote up
@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();
    }
  }
 
Example 24
Source Project: panama   Source File: AbstractClient.java    License: MIT License 5 votes vote down vote up
@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;
    }
 
Example 25
/**
 * 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());
        }
    }
}
 
Example 26
Source Project: netty-cookbook   Source File: BootstrapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 27
Source Project: qpid-jms   Source File: NettyTcpTransport.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 28
Source Project: kryonetty   Source File: Client.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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));
}
 
Example 29
Source Project: nomulus   Source File: ProbingActionTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 30
Source Project: netty-4.1.22   Source File: ObjectEchoClient.java    License: Apache License 2.0 5 votes vote down vote up
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();
    }
}