Java 类io.netty.bootstrap.Bootstrap 实例源码

项目:miracle-remote    文件:NettyClient.java   
@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();
}
项目:Nukkit-Java9    文件:UDPServerSocket.java   
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);
    }
}
项目:monica    文件:SocketClient.java   
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();
    }
}
项目:star-map    文件:StarClientProtocol.java   
@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());

            }
        });
    }
项目:fastdfs-spring-boot    文件:FastdfsPoolGroup.java   
@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
    );
}
项目:upgradeToy    文件:SimpleClient.java   
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();
            }
        }
    });
}
项目:Limitart    文件:BinaryClient.java   
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());
}
项目:io-comparison    文件:NettyClient.java   
@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();
}
项目:Ashbringer-load    文件:NettyShooter.java   
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);
                });
    }
项目:Mods    文件:TF2UdpServer.java   
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();
    }
}
项目:talchain    文件:UdpTest.java   
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();
}
项目:drift    文件:ConnectionFactory.java   
@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));
    }
}
项目:skylla    文件:SimpleSkyllaClient.java   
@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();
    }
}
项目:dubbo-transaction    文件:NettyClientFacade.java   
/**
 * 获取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();
}
项目:onedatashare    文件:HTTPBuilder.java   
/** 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());
  }
}
项目:nettyRpc    文件:ClientConnectionPool.java   
/**
 * 初始化连接池
 */
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);
    });
}
项目:kcp-netty    文件:TcpRttClient.java   
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();
    }
}
项目:push    文件:Client.java   
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;
}
项目:rskj    文件:PeerClient.java   
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();
}
项目:ClusterDeviceControlPlatform    文件:NettyClient.java   
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);
    });
}
项目:ClusterDeviceControlPlatform    文件:NettyServer.java   
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();
}
项目:ClusterDeviceControlPlatform    文件:NettyClient.java   
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();
    }
}
项目:fresco_floodlight    文件:BootstrapClient.java   
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);
}
项目:cardea    文件:CardeaServerFrontEndHandler.java   
@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();
        }
    });
}
项目:Jenisys3    文件:UDPServerSocket.java   
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);
    }
}
项目:Stork    文件:HTTPBuilder.java   
/** 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());
  }
}
项目:fresco_floodlight    文件:RPCService.java   
/**
 * 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);
}
项目:candlelight    文件:NetworkEngine.java   
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;
}
项目:NettyStudy    文件:EchoClient.java   
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();
    }
}
项目:ditb    文件:AsyncRpcChannel.java   
/**
 * 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())));
}
项目:guereza    文件:NettyEventBusClient.java   
@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;
}
项目:firebase-admin-java    文件:NettyWebSocketClient.java   
@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);
  }
}
项目:nearenough    文件:NettyClient.java   
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();
}
项目:angel    文件:ChannelManager.java   
/**
 * 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;
}
项目:EMC    文件:OAuthNetworkManager.java   
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;
}
项目:waterrower-core    文件:RxtxCommunicationService.java   
/**
 * 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);
}
项目:GitHub    文件:NettyHttpClient.java   
@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);
}
项目:Backmemed    文件:NetworkManager.java   
/**
 * 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;
}
项目:BedrockProxy    文件:RakNetServer.java   
/**
 * 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);
    }
}
项目:PetiteRPC    文件:NettyConnector.java   
@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);
}