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   Source Code and License 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: fastdfs-spring-boot   File: FastdfsPoolGroup.java   Source Code and License 7 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 3
Project: io-comparison   File: NettyClient.java   Source Code and License 7 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 4
Project: miracle-remote   File: NettyClient.java   Source Code and License 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 5
Project: Nukkit-Java9   File: UDPServerSocket.java   Source Code and License 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 6
Project: upgradeToy   File: SimpleClient.java   Source Code and License 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   Source Code and License 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: Mods   File: TF2UdpServer.java   Source Code and License 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 9
Project: talchain   File: UdpTest.java   Source Code and License 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 10
Project: drift   File: ConnectionFactory.java   Source Code and License 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 11
Project: skylla   File: SimpleSkyllaClient.java   Source Code and License 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 12
Project: dubbo-transaction   File: NettyClientFacade.java   Source Code and License 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 13
Project: onedatashare   File: HTTPBuilder.java   Source Code and License 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 14
Project: nettyRpc   File: ClientConnectionPool.java   Source Code and License 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 15
Project: kcp-netty   File: TcpRttClient.java   Source Code and License 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 16
Project: push   File: Client.java   Source Code and License 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 17
Project: rskj   File: PeerClient.java   Source Code and License 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 18
Project: ClusterDeviceControlPlatform   File: NettyClient.java   Source Code and License 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 19
Project: ClusterDeviceControlPlatform   File: NettyServer.java   Source Code and License 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 20
Project: ClusterDeviceControlPlatform   File: NettyClient.java   Source Code and License 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 21
Project: fresco_floodlight   File: BootstrapClient.java   Source Code and License 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 22
Project: cardea   File: CardeaServerFrontEndHandler.java   Source Code and License 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 23
Project: Jenisys3   File: UDPServerSocket.java   Source Code and License 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 24
Project: Stork   File: HTTPBuilder.java   Source Code and License 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 25
Project: fresco_floodlight   File: RPCService.java   Source Code and License 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 26
Project: candlelight   File: NetworkEngine.java   Source Code and License 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 27
Project: NettyStudy   File: EchoClient.java   Source Code and License 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 28
Project: ditb   File: AsyncRpcChannel.java   Source Code and License 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 29
Project: guereza   File: NettyEventBusClient.java   Source Code and License 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 30
Project: firebase-admin-java   File: NettyWebSocketClient.java   Source Code and License 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 31
Project: nearenough   File: NettyClient.java   Source Code and License 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 32
Project: angel   File: ChannelManager.java   Source Code and License 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 33
Project: EMC   File: OAuthNetworkManager.java   Source Code and License 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 34
Project: waterrower-core   File: RxtxCommunicationService.java   Source Code and License 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 35
Project: GitHub   File: NettyHttpClient.java   Source Code and License 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 36
Project: Backmemed   File: NetworkManager.java   Source Code and License 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 37
Project: BedrockProxy   File: RakNetServer.java   Source Code and License 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 38
Project: monica   File: SocketClient.java   Source Code and License 5 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 39
Project: PetiteRPC   File: NettyConnector.java   Source Code and License 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);
}
 
Example 40
Project: kcp-netty   File: KcpRttClient.java   Source Code and License 5 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(UkcpClientChannel.class)
                .handler(new ChannelInitializer<UkcpChannel>() {
                    @Override
                    public void initChannel(UkcpChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new KcpRttClientHandler(COUNT));
                    }
                });
        ChannelOptionHelper.nodelay(b, true, 20, 2, true)
                .option(UkcpChannelOption.UKCP_MTU, 512);

        // 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 41
Project: JRediClients   File: RedisClient.java   Source Code and License 5 votes vote down vote up
private Bootstrap createBootstrap(RedisClientConfig config, Type type) {
    Bootstrap bootstrap = new Bootstrap()
                    .channel(config.getSocketChannelClass())
                    .group(config.getGroup())
                    .remoteAddress(addr);

    bootstrap.handler(new RedisChannelInitializer(bootstrap, config, this, channels, type));
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, config.isKeepAlive());
    bootstrap.option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay());
    return bootstrap;
}
 
Example 42
Project: nitmproxy   File: BackendChannelBootstrap.java   Source Code and License 5 votes vote down vote up
public ChannelFuture connect(ChannelHandlerContext fromCtx, NitmProxyMaster master, ConnectionInfo connectionInfo,
                             ChannelHandler handler) {
    return new Bootstrap()
            .group(fromCtx.channel().eventLoop())
            .channel(fromCtx.channel().getClass())
            .handler(handler)
            .connect(connectionInfo.getServerAddr().getHost(),
                     connectionInfo.getServerAddr().getPort());
}
 
Example 43
Project: elasticsearch_my   File: Netty4Transport.java   Source Code and License 5 votes vote down vote up
private Bootstrap createBootstrap() {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX)));
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.handler(getClientChannelInitializer());

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(defaultConnectionProfile.getConnectTimeout().millis()));
    bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.getBytes() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.getBytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.getBytes() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.getBytes()));
    }

    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);

    bootstrap.validate();

    return bootstrap;
}
 
Example 44
Project: Ashbringer-load   File: NettyShooter.java   Source Code and License 5 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 45
Project: kcp-netty   File: EchoClient.java   Source Code and License 5 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(UkcpClientChannel.class)
                .handler(new ChannelInitializer<UkcpChannel>() {
                    @Override
                    public void initChannel(UkcpChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new EchoClientHandler());
                    }
                });
        ChannelOptionHelper.nodelay(b, true, 20, 2, true)
                .option(UkcpChannelOption.UKCP_MTU, 512);

        // 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 46
Project: hadoop   File: SimpleHttpProxyHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
 
Example 47
Project: neoscada   File: Client.java   Source Code and License 5 votes vote down vote up
public Client ( final SocketAddress address, final ConnectionStateListener listener, final ProtocolOptions options, final List<ClientModule> modules )
{
    this.address = address;
    this.options = options;

    this.listener = listener;

    this.manager = new MessageManager ( options );

    this.group = new NioEventLoopGroup ();

    this.bootstrap = new Bootstrap ();
    this.bootstrap.group ( this.group );
    this.bootstrap.channel ( NioSocketChannel.class );

    this.bootstrap.handler ( new ChannelInitializer<SocketChannel> () {

        @Override
        protected void initChannel ( final SocketChannel ch ) throws Exception
        {
            handleInitChannel ( ch );
        }
    } );

    this.modules = modules.toArray ( new ClientModule[modules.size ()] );
    this.executor = Executors.newSingleThreadExecutor ( new NamedThreadFactory ( "IEC60870Client/" + address ) );

    for ( final ClientModule module : modules )
    {
        module.initializeClient ( this, this.manager );
    }
}
 
Example 48
Project: DistributedID-SDK   File: AbstractClient.java   Source Code and License 5 votes vote down vote up
public void init() {
    asyncResponse = new ConcurrentHashMap<>();
    workGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 10, new ThreadFactory() {
        private AtomicInteger index = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "WORK_" + index.incrementAndGet());
        }
    });

    b = new Bootstrap();
}
 
Example 49
Project: GoPush   File: Node.java   Source Code and License 5 votes vote down vote up
private Bootstrap configBootstrap() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap
            .group(group)
            .remoteAddress(intranetIp, nodePort)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(channelInitializer());
    return bootstrap;
}
 
Example 50
Project: hekate   File: NettyClient.java   Source Code and License 5 votes vote down vote up
private void setOpts(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    setUserOpt(bootstrap, ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    setUserOpt(bootstrap, ChannelOption.TCP_NODELAY, tcpNoDelay);
    setUserOpt(bootstrap, ChannelOption.SO_RCVBUF, soReceiveBufferSize);
    setUserOpt(bootstrap, ChannelOption.SO_SNDBUF, soSendBufferSize);
    setUserOpt(bootstrap, ChannelOption.SO_REUSEADDR, soReuseAddress);
}
 
Example 51
Project: hekate   File: NettyClient.java   Source Code and License 5 votes vote down vote up
private <O> void setUserOpt(Bootstrap bootstrap, ChannelOption<O> opt, O value) {
    if (value != null) {
        if (trace) {
            log.trace("Setting option {} = {} [to={}]", opt, value, id());
        }

        bootstrap.option(opt, value);
    }
}
 
Example 52
Project: Backmemed   File: NetworkManager.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new NetworkManager from the server host and connect it to the server
 */
public static NetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    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;
    }

    ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
    {
        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((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new NettyVarint21FrameDecoder())).addLast((String)"decoder", (ChannelHandler)(new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new NettyVarint21FrameEncoder())).addLast((String)"encoder", (ChannelHandler)(new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
        }
    })).channel(oclass)).connect(address, serverPort).syncUninterruptibly();
    return networkmanager;
}
 
Example 53
Project: pumpkindb-java   File: Client.java   Source Code and License 5 votes vote down vote up
public void connect() {
    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 {
            ch.pipeline().addFirst(new LoggingHandler(LogLevel.DEBUG));

            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new FrameEncoder());

            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    messageHandler.accept(buf);
                }
            });
        }

    });


    ChannelFuture channelFuture = b.connect(host, port).syncUninterruptibly();

    channel = channelFuture.channel();

}
 
Example 54
Project: rskj   File: UDPServer.java   Source Code and License 5 votes vote down vote up
private Bootstrap createBootstrap(EventLoopGroup group) {
    return new Bootstrap().group(group).channel(NioDatagramChannel.class)
            .handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                public void initChannel(NioDatagramChannel ch)
                        throws Exception {
                    ch.pipeline().addLast(new PacketDecoder());
                    UDPChannel udpChannel = new UDPChannel(ch, peerExplorer);
                    peerExplorer.setUDPChannel(udpChannel);
                    ch.pipeline().addLast(udpChannel);
                }
            });
}
 
Example 55
Project: netty-dovakin-android-client   File: ConnectionWatcher.java   Source Code and License 5 votes vote down vote up
public ConnectionWatcher(Bootstrap bootstrap, Timer timer, String host, int port, boolean reconnect){
    this.bootstrap = bootstrap;
    this.timer = timer;
    this.host = host;
    this.port = port;
    this.reconnect = reconnect;
}
 
Example 56
Project: Cobweb   File: Client.java   Source Code and License 5 votes vote down vote up
private void shortConnection(){
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(channelInitializer);
        ChannelFuture future = b.connect(host, port).sync();
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 57
Project: util4j   File: PoolTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		final Bootstrap cb = new Bootstrap();
		cb.group(group).channel(NioSocketChannel.class);
		InetSocketAddress addr1 = new InetSocketAddress("10.0.0.10", 8888);
		InetSocketAddress addr2 = new InetSocketAddress("10.0.0.11", 8888);

		//连接池map
		ChannelPoolMap<InetSocketAddress, SimpleChannelPool> poolMap = new AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool>() {
		    @Override
		    protected SimpleChannelPool newPool(InetSocketAddress key) {
		        return new SimpleChannelPool(cb.remoteAddress(key), new TestChannelPoolHandler());
		    }
		};

		final SimpleChannelPool pool1 = poolMap.get(addr1);//取出連接addr1地址的连接池
		final SimpleChannelPool pool2 = poolMap.get(addr2);//取出連接addr2地址的连接池
		Future<Channel> f1 = pool1.acquire();//获取一个连接
		f1.addListener(new FutureListener<Channel>() {
		    @Override
		    public void operationComplete(Future<Channel> f) {
		        if (f.isSuccess()) {
		            Channel ch = f.getNow();
		           //连接地址1的某个channel
		            //使用连接发送消息
//		            ch.write(msg)
		            //用完释放
		            pool1.release(ch);
		        }
		    }
		});

	}
 
Example 58
Project: netty-connection-pool   File: BasicMultiNodeConnPool.java   Source Code and License 5 votes vote down vote up
protected Channel connect(final String addr)
throws Exception {
	final Bootstrap bootstrap = bootstraps.get(addr);
	if(bootstrap != null) {
		return bootstrap.connect().sync().channel();
	}
	return null;
}
 
Example 59
Project: netty-connection-pool   File: EpollConnDropTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp()
throws Exception {

	serverMock = new EpollConnDroppingServer(DEFAULT_PORT, FAIL_EVERY_CONN_ATTEMPT);

	final Semaphore concurrencyThrottle = new Semaphore(CONCURRENCY);
	group = new EpollEventLoopGroup();
	final Bootstrap bootstrap = new Bootstrap()
		.group(group)
		.channel(EpollSocketChannel.class)
		.handler(
			new ChannelInitializer<SocketChannel>() {
				@Override
				protected final void initChannel(final SocketChannel conn)
				throws Exception {
					conn.pipeline().addLast(new DummyClientChannelHandler());
				}
			}
		)
		.option(ChannelOption.SO_KEEPALIVE, true)
		.option(ChannelOption.SO_REUSEADDR, true)
		.option(ChannelOption.TCP_NODELAY, true);
	connPool = new BasicMultiNodeConnPool(
		concurrencyThrottle, NODES, bootstrap, CPH, DEFAULT_PORT, 0
	);
	connPool.preCreateConnections(CONCURRENCY);
}
 
Example 60
Project: netty-connection-pool   File: BasicMultiNodeConnPoolMock.java   Source Code and License 5 votes vote down vote up
public BasicMultiNodeConnPoolMock(
	final Semaphore concurrencyThrottle, final String[] nodes, final Bootstrap bootstrap,
	final ChannelPoolHandler connPoolHandler, final int defaultPort,
	final int connFailSeqLenLimit
) {
	super(
		concurrencyThrottle, nodes, bootstrap, connPoolHandler, defaultPort,
		connFailSeqLenLimit
	);
}