Java Code Examples for io.netty.bootstrap.Bootstrap

The following are top voted examples for showing how to use io.netty.bootstrap.Bootstrap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: star-map   File: StarClientProtocol.java   View source code 7 votes vote down vote up
@Override
    public void open() {
        EventLoopGroup eventLoop = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoop);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3 * 1000);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
//                        .addLast("logging",new LoggingHandler(LogLevel.INFO))
                        .addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))) // in 1
                        .addLast("handler", new ClientReadHandler()) // in 2
                        .addLast("encoder", new ObjectEncoder())// out 3
                        .addLast("idleStateHandler", new IdleStateHandler(0, 1, 0))
                        .addLast(new ClientIdleHandler());

            }
        });
    }
 
Example 2
Project: miracle-remote   File: NettyClient.java   View source code 6 votes vote down vote up
@Override
public void connect(final InetSocketAddress socketAddress) {
    workerGroup = new NioEventLoopGroup(workerGroupThreads);
    Bootstrap bootstrap = new Bootstrap();
    try {
        bootstrap
            .group(workerGroup)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(clientChannelInitializer);
    } catch (final Exception ex) {
        throw new ClientException(ex);
    }
    channel = bootstrap.connect(socketAddress.getAddress().getHostAddress(), socketAddress.getPort()).syncUninterruptibly().channel();
}
 
Example 3
Project: Nukkit-Java9   File: UDPServerSocket.java   View source code 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        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 4
Project: monica   File: SocketClient.java   View source code 6 votes vote down vote up
public void start(String ip, int port) 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 FileClientInitializer(sslCtx));
		Channel ch = b.connect(ip, port).sync().channel();
		ConfigurationContext.propMap.putIfAbsent(SOCKET_CHANNEL, ch);			
	}catch(Exception e){
		e.printStackTrace();
	}
}
 
Example 5
Project: fastdfs-spring-boot   File: FastdfsPoolGroup.java   View source code 6 votes vote down vote up
@Override
protected FastdfsPool newPool(InetSocketAddress addr) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("channel pool created : {}", addr);
    }

    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(loopGroup);
    bootstrap.remoteAddress(addr);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    return new FastdfsPool(
            bootstrap,
            readTimeout,
            idleTimeout,
            maxConnPerHost
    );
}
 
Example 6
Project: upgradeToy   File: SimpleClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup())
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
                future.channel().close();
            }
        }
    });
}
 
Example 7
Project: Limitart   File: BinaryClient.java   View source code 6 votes vote down vote up
private BinaryClient(BinaryClientBuilder builder) throws Exception {
	this.clientName = builder.clientName;
	this.remoteAddress = Objects.requireNonNull(builder.remoteAddress, "remoteAddress");
	this.autoReconnect = builder.autoReconnect;
	this.decoder = Objects.requireNonNull(builder.decoder, "decoder");
	this.encoder = Objects.requireNonNull(builder.encoder, "encoder");
	this.factory = Objects.requireNonNull(builder.factory, "factory");
	this.onChannelStateChanged = builder.onChannelStateChanged;
	this.onExceptionCaught = builder.onExceptionCaught;
	this.onConnectionEffective = builder.onConnectionEffective;
	this.dispatchMessage = builder.dispatchMessage;
	this.heartIntervalSec = builder.heartIntervalSec;
	// 内部消息注册
	factory.registerMsg(new ConnectionValidateServerHandler())
			.registerMsg(new ConnectionValidateSuccessServerHandler()).registerMsg(new HeartServerHandler());
	decodeUtil = SymmetricEncryptionUtil.getDecodeInstance(remoteAddress.getPass());
	bootstrap = new Bootstrap();
	bootstrap.channel(NioSocketChannel.class);
	log.info(clientName + " nio init");
	bootstrap.group(group).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
			.handler(new ChannelInitializerImpl());
}
 
Example 8
Project: io-comparison   File: NettyClient.java   View source code 6 votes vote down vote up
@Override
public void connect() throws IOException, InterruptedException {
    workerGroup = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(
                    //new LoggingHandler(LogLevel.INFO),
                    new MsgEncoder(),
                    new MsgDecoder(),
                    new NettyClientHandler()
            );
        }
    });

    ChannelFuture f = b.connect(address, port).sync();
    channel = f.channel();
}
 
Example 9
Project: Ashbringer-load   File: NettyShooter.java   View source code 6 votes vote down vote up
public void shoot(ShootComplete shootComplete) {

        Bootstrap b = new Bootstrap();

        SslContext sslContext = null;
        if (ssl) {
            try {
                sslContext = SslContextBuilder.forClient()
                        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
            } catch (SSLException e) {
                e.printStackTrace();
            }
        }

        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new HttpClientInitializer(sslContext));

        // Make the connection attempt.
        b.connect(host, port).addListener(
                (ChannelFutureListener) channelFuture -> {
                    sendHttpRequest(channelFuture, shootComplete);
                });
    }
 
Example 10
Project: Mods   File: TF2UdpServer.java   View source code 6 votes vote down vote up
public void run() {
	try {
		Bootstrap boot = new Bootstrap();
		boot.group(group)
		 .channel(NioDatagramChannel.class)
		 .handler(new ChannelInitializer<DatagramChannel>() {

			@Override
			protected void initChannel(DatagramChannel ch) throws Exception {
				channel = ch;
				ch.pipeline().addLast(new UdpChannelHandlerServer(TF2UdpServer.this));
			}
			 
		 });
		boot.bind(port).sync().channel().closeFuture();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 11
Project: talchain   File: UdpTest.java   View source code 6 votes vote down vote up
public Channel create(String bindAddr, int port) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);

    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new PacketDecoder());
                SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
                nodeManager.setMessageSender(messageHandler);
                ch.pipeline().addLast(messageHandler);
            }
        });

    return b.bind(bindAddr, port).sync().channel();
}
 
Example 12
Project: drift   File: ConnectionFactory.java   View source code 6 votes vote down vote up
@Override
public Future<Channel> getConnection(HostAndPort address)
{
    try {
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .option(CONNECT_TIMEOUT_MILLIS, saturatedCast(connectTimeout.toMillis()))
                .handler(new ThriftClientInitializer(
                        messageFraming,
                        messageEncoding,
                        requestTimeout,
                        socksProxy,
                        sslContextSupplier));

        Promise<Channel> promise = group.next().newPromise();
        bootstrap.connect(new InetSocketAddress(address.getHost(), address.getPort()))
                .addListener((ChannelFutureListener) future -> notifyConnect(future, promise));
        return promise;
    }
    catch (Throwable e) {
        return group.next().newFailedFuture(new TTransportException(e));
    }
}
 
Example 13
Project: skylla   File: SimpleSkyllaClient.java   View source code 6 votes vote down vote up
@Override
public void connect() {
    this.workerGroup = NettyUtils.createEventLoopGroup(4);

    Class<? extends Channel> channelClazz = NettyUtils.getChannel();
    ChannelHandler channelInitializer = new SkyllaChannelInitializer(this.config.getProtocol());

    Bootstrap bootstrap = new Bootstrap();

    try {
        channel = bootstrap
                .channel(channelClazz)
                .group(this.workerGroup)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_BACKLOG, 50)
                .handler(channelInitializer)
                .connect(this.config.getServerHost(), this.config.getServerPort())
                .sync().channel();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: dubbo-transaction   File: NettyClientFacade.java   View source code 6 votes vote down vote up
/**
 * 获取channel
 * @param ip
 * @param port
 * @return
 * @throws InterruptedException
 */
private Channel getChannel(String ip,String port) throws InterruptedException {
    String channelKey=getUniqKey(ip, port);
    ArrayBlockingQueue<Channel> aq=putIfAbsent(NETTY_CHANNEL,channelKey, new ArrayBlockingQueue<Channel>(BOOTSTRAP_POOL_SIZE*CHANNEL_POOL_SIZE));
    aq=null==aq?NETTY_CHANNEL.get(channelKey):aq;
    Channel channel=aq.poll(100, TimeUnit.MILLISECONDS);
    //判断是否已经关闭的channel,如果是,不再放入连接池,重新申请连接
    if(null!=channel&&(!channel.isActive()||!channel.isOpen()||!channel.isWritable())){
        channel.disconnect();
        channel=null;
    }
    Bootstrap bootstrap=null==channel?getBootstrap(ip, port):null;
    if(null!=bootstrap){
        ChannelFuture f =bootstrap.connect(ip,Integer.parseInt(port)).sync();
        if (f.isSuccess())channel=f.channel();
    }

    return null!=channel?channel:aq.take();
}
 
Example 15
Project: onedatashare   File: HTTPBuilder.java   View source code 6 votes vote down vote up
/** Constructor that sets up the connection */
public HTTPBuilder(HTTPSession session) {
  try {
    boot = new Bootstrap();
    boot.group(session.workGroup)
      .channel(HTTPChannel.class)
      .handler(new HTTPInitializer(session.uri.scheme(), this));

    // Channel setup
    onConnectBell = new Bell<Void>();
    setUri(session.uri);
    setupWithTest();

    // Tap bells queue setup
    tapBellQueue = new ConcurrentLinkedQueue<Bell<Void>>();
  } catch (HTTPException e) {
    System.err.println(e.getMessage());
  }
}
 
Example 16
Project: nettyRpc   File: ClientConnectionPool.java   View source code 6 votes vote down vote up
/**
 * 初始化连接池
 */
public void init() {
    bootstrap = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new LoggingHandler());
    //所有的公用一个eventloopgroup, 对于客户端来说应该问题不大!
    poolMap = new AbstractChannelPoolMap<InetSocketAddress, FixedChannelPool>() {
        @Override
        protected FixedChannelPool newPool(InetSocketAddress key) {
            return new FixedChannelPool(bootstrap.remoteAddress(key), new FixedChannelPoolHandler(), 2);
        }
    };
    //预先建立好链接
    serverListConfig.getAddressList().stream().forEach(address -> {
        poolMap.get(address);
    });
}
 
Example 17
Project: kcp-netty   File: TcpRttClient.java   View source code 6 votes vote down vote up
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)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new TcpRttDecoder())
                                .addLast(new TcpRttClientHandler(COUNT));
                    }
                }).option(ChannelOption.TCP_NODELAY, true);

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

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
 
Example 18
Project: push   File: Client.java   View source code 6 votes vote down vote up
public void run() {
	workerGroup = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(workerGroup);
		b.channel(NioSocketChannel.class);
		// b.option(ChannelOption.SO_KEEPALIVE, true);
		b.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
				pipeline.addLast("decoder", new MsgPackDecode());
				pipeline.addLast("encoder", new MsgPackEncode());
				pipeline.addLast(new ClientHandler());
			}
		});
		channel = b.connect(clientProperties.getServerHost(), clientProperties.getServerPort()).sync().channel();
		status = Status.START;
		channel.closeFuture().sync();
	} catch (Exception e) {
		e.printStackTrace();
	}
	status = Status.STOP;
}
 
Example 19
Project: rskj   File: PeerClient.java   View source code 6 votes vote down vote up
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
    ethereumListener.trace("Connecting to: " + host + ":" + port);

    EthereumChannelInitializer ethereumChannelInitializer = ethereumChannelInitializerFactory.newInstance(remoteId);
    ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
    b.remoteAddress(host, port);

    b.handler(ethereumChannelInitializer);

    // Start the client.
    return b.connect();
}
 
Example 20
Project: ClusterDeviceControlPlatform   File: NettyClient.java   View source code 6 votes vote down vote up
public void start(String hostName, int port) {
    Executors.newSingleThreadExecutor().submit(() -> {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new KyChannelInitializer());
        if (hostName != null && !hostName.equals(""))
            bootstrap.remoteAddress(new InetSocketAddress(hostName, port));
        else
            bootstrap.remoteAddress(new InetSocketAddress(port));
        ChannelFuture channelFuture = null;

        try {
            channelFuture = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        startListenerHandle(channelFuture, launchListener);
    });
}
 
Example 21
Project: ClusterDeviceControlPlatform   File: NettyServer.java   View source code 6 votes vote down vote up
public void start() {
    new Thread(() -> {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(30232)) //"woodswang",
                .handler(KyChannelInitializer.newInstance());
        ChannelFuture channelFuture = null;

        try {
            channelFuture = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        startListenerHandle(channelFuture, launchListener);
    }).start();
}
 
Example 22
Project: ClusterDeviceControlPlatform   File: NettyClient.java   View source code 6 votes vote down vote up
private void startClient(String hostName, int port, int id) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
            .attr(channelId, id)
            .channel(NioSocketChannel.class)
            .handler(clientChannelInitializer);
    if (hostName != null && !"".equals(hostName)) {
        bootstrap.remoteAddress(new InetSocketAddress(hostName, port));
    } else {
        bootstrap.remoteAddress(new InetSocketAddress(port));
    }
    try {
        bootstrap.connect().sync().addListener(future -> logger.info("Channel「" + id + "」" + "已连接"));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 23
Project: fresco_floodlight   File: BootstrapClient.java   View source code 6 votes vote down vote up
public void init() throws SyncException {
    cg = new DefaultChannelGroup("Cluster Bootstrap", GlobalEventExecutor.INSTANCE);

    workerExecutor = new NioEventLoopGroup();
    timer = new HashedWheelTimer();
    
    bootstrap = new Bootstrap()
    .group(workerExecutor)
    .channel(NioSocketChannel.class)
    .option(ChannelOption.SO_REUSEADDR, true)
    .option(ChannelOption.SO_KEEPALIVE, true)
    .option(ChannelOption.TCP_NODELAY, true)
    .option(ChannelOption.SO_SNDBUF, RPCService.SEND_BUFFER_SIZE)
    .option(ChannelOption.SO_RCVBUF, RPCService.SEND_BUFFER_SIZE)
    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, RPCService.CONNECT_TIMEOUT);
    
    pipelineFactory = new BootstrapChannelInitializer(timer, this);
    bootstrap.handler(pipelineFactory);
}
 
Example 24
Project: cardea   File: CardeaServerFrontEndHandler.java   View source code 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop())
            .channel(ctx.channel().getClass())
            .handler(new CardeaServerBackendHandler(inboundChannel))
            .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(host, port);

    outboundChannel = f.channel();

    f.addListener((ChannelFutureListener) 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 25
Project: Jenisys3   File: UDPServerSocket.java   View source code 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        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 26
Project: Stork   File: HTTPBuilder.java   View source code 6 votes vote down vote up
/** Constructor that sets up the connection */
public HTTPBuilder(HTTPSession session) {
  try {
    boot = new Bootstrap();
    boot.group(session.workGroup)
      .channel(HTTPChannel.class)
      .handler(new HTTPInitializer(session.uri.scheme(), this));

    // Channel setup
    onConnectBell = new Bell<Void>();
    setUri(session.uri);
    setupWithTest();

    // Tap bells queue setup
    tapBellQueue = new ConcurrentLinkedQueue<Bell<Void>>();
  } catch (HTTPException e) {
    System.err.println(e.getMessage());
  }
}
 
Example 27
Project: fresco_floodlight   File: RPCService.java   View source code 6 votes vote down vote up
/**
 * Connect to remote servers.  We'll initiate the connection to
 * any nodes with a lower ID so that there will be a single connection
 * between each pair of nodes which we'll use symmetrically
 */
protected void startClients(RPCChannelInitializer channelInitializer) {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)
    .channel(NioSocketChannel.class)
    .option(ChannelOption.SO_REUSEADDR, true)
    .option(ChannelOption.SO_KEEPALIVE, true)
    .option(ChannelOption.TCP_NODELAY, true)
    .option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE)
    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
    .handler(channelInitializer);
    clientBootstrap = bootstrap;

    ScheduledExecutorService ses = 
            syncManager.getThreadPool().getScheduledExecutor();
    reconnectTask = new SingletonTask(ses, new ConnectTask());
    reconnectTask.reschedule(0, TimeUnit.SECONDS);
}
 
Example 28
Project: candlelight   File: NetworkEngine.java   View source code 6 votes vote down vote up
public NetworkDispatcher connectToLocal(SocketAddress address)
{
	NetworkDispatcher dispatch = new NetworkDispatcher(this, NetworkSide.CLIENT);

	final EventLoopGroup boss = new DefaultEventLoopGroup();
	final Bootstrap b = new Bootstrap()
			.group(boss)
			.handler(new ChannelInitializer<Channel>() {
				@Override
				protected void initChannel(Channel ch) throws Exception
				{
					ch.pipeline().addLast(dispatch);
				}
			})
			.channel(LocalChannel.class);

	//Connect and wait until done
	b.connect(address).syncUninterruptibly();

	return dispatch;
}
 
Example 29
Project: NettyStudy   File: EchoClient.java   View source code 6 votes vote down vote up
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
         .channel(NioSocketChannel.class)
         .remoteAddress(new InetSocketAddress(host, port))
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) 
                 throws Exception {
                 ch.pipeline().addLast(
                         new EchoClientHandler());
             }
         });

        ChannelFuture f = bootstrap.connect().sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 30
Project: ditb   File: AsyncRpcChannel.java   View source code 6 votes vote down vote up
/**
 * Constructor for netty RPC channel
 *
 * @param bootstrap to construct channel on
 * @param client    to connect with
 * @param ticket of user which uses connection
 *               @param serviceName name of service to connect to
 * @param address to connect to
 */
public AsyncRpcChannel(Bootstrap bootstrap, final AsyncRpcClient client, User ticket, String
    serviceName, InetSocketAddress address) {
  this.client = client;

  this.ticket = ticket;
  this.serviceName = serviceName;
  this.address = address;

  this.channel = connect(bootstrap).channel();

  name = ("IPC Client (" + channel.hashCode() + ") to " +
      address.toString() +
      ((ticket == null) ?
          " from unknown user" :
          (" from " + ticket.getName())));
}
 
Example 31
Project: guereza   File: NettyEventBusClient.java   View source code 6 votes vote down vote up
@Override
public boolean start() {
    if (nettyChannel != null)
        return false;

    group = new NioEventLoopGroup();
    try {
        final Bootstrap bootstrap = new io.netty.bootstrap.Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer(this::trigger));

        nettyChannel = bootstrap.connect(host, port).sync().channel();
    } catch (final Exception e) {
        LOGGER.error("Impossible to connect to {}:{}", host, port);
        return false;
    }
    LOGGER.info("Connected on {}:{}", host, port);

    return true;
}
 
Example 32
Project: firebase-admin-java   File: NettyWebSocketClient.java   View source code 5 votes vote down vote up
@Override
public void connect() {
  checkState(channel == null, "channel already initialized");
  try {
    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init((KeyStore) null);
    final SslContext sslContext = SslContextBuilder.forClient()
        .trustManager(trustFactory).build();
    Bootstrap bootstrap = new Bootstrap();
    final int port = uri.getPort() != -1 ? uri.getPort() : DEFAULT_WSS_PORT;
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
            p.addLast(
                new HttpClientCodec(),
                // Set the max size for the HTTP responses. This only applies to the WebSocket
                // handshake response from the server.
                new HttpObjectAggregator(32 * 1024),
                channelHandler);
          }
        });

    ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), port);
    this.channel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
              eventHandler.onError(future.cause());
            }
          }
        }
    );
  } catch (Exception e) {
    eventHandler.onError(e);
  }
}
 
Example 33
Project: nearenough   File: NettyClient.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, NoSuchAlgorithmException {
  InetSocketAddress addr = new InetSocketAddress(GOOGLE_SERVER_HOST, GOOGLE_SERVER_PORT);

  System.out.printf("Sending request to %s\n", addr);

  // Below is Netty boilerplate for setting-up an event loop and registering a handler

  NioEventLoopGroup group = new NioEventLoopGroup();
  Bootstrap bootstrap = new Bootstrap()
      .group(group)
      .remoteAddress(addr)
      .channel(NioDatagramChannel.class)
      .handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        protected void initChannel(NioDatagramChannel ch) throws Exception {
          ch.pipeline()
              .addLast(new ReadTimeoutHandler(5))
              .addLast(new RequestHandler(addr));
        }
      });

  ChannelFuture connectFuture = bootstrap.connect();
  connectFuture.addListener(fut -> {
    if (!fut.isSuccess()) {
      System.out.println("Connect fail:");
      System.out.println(fut.cause().getMessage());
    }
  });

  connectFuture.channel().closeFuture().sync();
  group.shutdownGracefully();
}
 
Example 34
Project: angel   File: ChannelManager.java   View source code 5 votes vote down vote up
/**
 * Create a new ChannelManager.
 *
 * @param bootstrap netty client bootstrap
 */
public ChannelManager(Bootstrap bootstrap, int maxPoolSize) {
  this.bootstrap = bootstrap;
  this.locToChannelPoolMap = new HashMap<Location, GenericObjectPool<Channel>>();
  this.lock = new ReentrantLock();
  this.maxPoolSize = maxPoolSize;
}
 
Example 35
Project: EMC   File: OAuthNetworkManager.java   View source code 5 votes vote down vote up
public static OAuthNetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort,
		boolean useNativeTransport, OAuthCallback callback) {
	final OAuthNetworkManager networkmanager = new OAuthNetworkManager(EnumPacketDirection.CLIENTBOUND, callback);
	Class<? extends SocketChannel> oclass;
	LazyLoadBase<? extends EventLoopGroup> lazyloadbase;

	if (Epoll.isAvailable() && useNativeTransport) {
		oclass = EpollSocketChannel.class;
		lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
	} else {
		oclass = NioSocketChannel.class;
		lazyloadbase = CLIENT_NIO_EVENTLOOP;
	}

	(new Bootstrap()).group(lazyloadbase.getValue()).handler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel p_initChannel_1_) throws Exception {
			try {
				p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
			} catch (ChannelException var3) {
				;
			}

			p_initChannel_1_.pipeline().addLast("timeout", new ReadTimeoutHandler(30))
					.addLast("splitter", new NettyVarint21FrameDecoder())
					.addLast("decoder", new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))
					.addLast("prepender", new NettyVarint21FrameEncoder())
					.addLast("encoder", new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))
					.addLast("packet_handler", networkmanager);
		}
	}).channel(oclass).connect(address, serverPort).syncUninterruptibly();
	return networkmanager;
}
 
Example 36
Project: waterrower-core   File: RxtxCommunicationService.java   View source code 5 votes vote down vote up
/**
 * A communication service that manages the serial connection.
 * It can receive and send serial messages via RXTX.
 *
 * @param bootstrap The bootstrap, not null.
 * @param channelInitializer The channel initializer, not null.
 */
public RxtxCommunicationService(Bootstrap bootstrap, RxtxChannelInitializer channelInitializer) {
    requireNonNull(bootstrap);
    requireNonNull(channelInitializer);

    this.bootstrap = bootstrap;
    this.bootstrap.group(new OioEventLoopGroup());
    this.bootstrap.channel(RxtxChannel.class);

    channelInitializer.setRxTxSerialHandler(serialHandler);

    this.bootstrap.handler(channelInitializer);
}
 
Example 37
Project: GitHub   File: NettyHttpClient.java   View source code 5 votes vote down vote up
@Override public void prepare(final Benchmark benchmark) {
  this.concurrencyLevel = benchmark.concurrencyLevel;
  this.targetBacklog = benchmark.targetBacklog;

  ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
    @Override public void initChannel(SocketChannel channel) throws Exception {
      ChannelPipeline pipeline = channel.pipeline();

      if (benchmark.tls) {
        SslClient sslClient = SslClient.localhost();
        SSLEngine engine = sslClient.sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        pipeline.addLast("ssl", new SslHandler(engine));
      }

      pipeline.addLast("codec", new HttpClientCodec());
      pipeline.addLast("inflater", new HttpContentDecompressor());
      pipeline.addLast("handler", new HttpChannel(channel));
    }
  };

  bootstrap = new Bootstrap();
  bootstrap.group(new NioEventLoopGroup(concurrencyLevel))
      .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
      .channel(NioSocketChannel.class)
      .handler(channelInitializer);
}
 
Example 38
Project: Backmemed   File: NetworkManager.java   View source code 5 votes vote down vote up
/**
 * Prepares a clientside NetworkManager: establishes a connection to the socket supplied and configures the channel
 * pipeline. Returns the newly created instance.
 */
public static NetworkManager provideLocalClient(SocketAddress address)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)CLIENT_LOCAL_EVENTLOOP.getValue())).handler(new ChannelInitializer<Channel>()
    {
        protected void initChannel(Channel p_initChannel_1_) throws Exception
        {
            p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
        }
    })).channel(LocalChannel.class)).connect(address).syncUninterruptibly();
    return networkmanager;
}
 
Example 39
Project: BedrockProxy   File: RakNetServer.java   View source code 5 votes vote down vote up
/**
 * Constructs a <code>RakNetServer</code> with the specified port, maximum
 * amount connections, maximum transfer unit, and <code>Identifier</code>.
 *
 * @param port                the server port.
 * @param maxConnections      the maximum amount of connections.
 * @param maximumTransferUnit the maximum transfer unit.
 * @param identifier          the <code>Identifier</code>.
 */
public RakNetServer(int port, int maxConnections, int maximumTransferUnit, Identifier identifier) {
    // Set server data
    this.guid = new Random().nextLong();
    this.timestamp = System.currentTimeMillis();
    this.port = port;
    this.maxConnections = maxConnections;
    this.maximumTransferUnit = maximumTransferUnit;
    this.broadcastingEnabled = true;
    this.identifier = identifier;

    // Initiate bootstrap data
    this.bootstrap = new Bootstrap();
    this.group = new NioEventLoopGroup();
    this.handler = new RakNetServerHandler(this);

    // Set listener
    this.listener = this;

    // Create session map
    this.sessions = new ConcurrentHashMap<InetSocketAddress, RakNetClientSession>();

    // Check maximum transfer unit
    if (this.maximumTransferUnit < RakNet.MINIMUM_TRANSFER_UNIT) {
        throw new IllegalArgumentException(
                "Maximum transfer unit can be no smaller than " + RakNet.MINIMUM_TRANSFER_UNIT);
    }
}
 
Example 40
Project: PetiteRPC   File: NettyConnector.java   View source code 5 votes vote down vote up
@Override
public Connection connect(Address address, Consumer<TransportChannel> successEvent) {
	Bootstrap bootstrap = bootstrap();
	final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort());	
	
	bootstrap.handler(new ChannelInitializer<Channel>() {

		@Override
		protected void initChannel(Channel ch) throws Exception {
			ch.pipeline()
			.addLast(new Encoder(serializer))
			.addLast(new Decoder(serializer))
			.addLast(new ConsumerHandler());
		}
		
	});
	
	ChannelFuture connectChannelFuture = bootstrap.connect(socketAddress);
	connectChannelFuture.addListener(new ChannelFutureListener() {
           
           @Override
           public void operationComplete(ChannelFuture future) throws Exception {
               if (future.isSuccess()) {
               		TransportChannel transportChannel = NettyChannel.getInstance(future.channel());
               		successEvent.accept(transportChannel);
               }
           }
       });
	return new NettyConnection(connectChannelFuture);
}