Java Code Examples for io.netty.channel.socket.nio.NioSocketChannel

The following are top voted examples for showing how to use io.netty.channel.socket.nio.NioSocketChannel. 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: CentauriCloud   File: Client.java   Source Code and License 6 votes vote down vote up
public void start() throws InterruptedException {
	final EventLoopGroup workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup();

	try {
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(workerGroup)
				.channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class)
				.handler(new OpenCloudChannelInitializer(this))
				.connect(this.host, this.port).sync().channel().closeFuture().syncUninterruptibly();
	} catch (Exception ex) {
		if (ex.getClass().getSimpleName().equals("AnnotatedConnectException")) {
			System.err.println("Cannot connect to master!");
			channel.close();
		} else {
			ex.printStackTrace();
		}
	} finally {
		workerGroup.shutdownGracefully();
		System.out.println("Netty client stopped");
		Runtime.getRuntime().halt(0);
	}
}
 
Example 5
Project: TakinRPC   File: RemotingNettyClient.java   Source Code and License 6 votes vote down vote up
public void start() {
    bootstrap.group(group).channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            //                ch.pipeline().addLast(new IdleStateHandler(1, 1, 5));
            ch.pipeline().addLast(new KyroMsgDecoder());
            ch.pipeline().addLast(new KyroMsgEncoder());
            ch.pipeline().addLast(new ClientHandler());
        }
    });

    new ScheduledThreadPoolExecutor(1).scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            scanResponseTable(3000);
        }
    }, 1000, 1000, TimeUnit.MILLISECONDS);
}
 
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: ndbc   File: ChannelSupplier.java   Source Code and License 6 votes vote down vote up
private final Future<Void> bootstrap(final NettyChannel channel) {
  final Promise<Void> p = Promise.apply();
  new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
      .option(ChannelOption.SO_KEEPALIVE, true)
      .option(ChannelOption.AUTO_READ, false)
      .handler(new ChannelInitializer<io.netty.channel.Channel>() {
        @Override
        protected void initChannel(final io.netty.channel.Channel ch) throws Exception {
          ch.pipeline().addLast(new MessageDecoder(), new MessageEncoder(),
              new FlowControlHandler(), channel);
        }
      })
      .connect(new InetSocketAddress(host, port))
      .addListener(future -> p.become(Future.VOID));
  return p;
}
 
Example 9
Project: talchain   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 = ctx.getBean(EthereumChannelInitializer.class, 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 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: 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 12
Project: im   File: EchoClient.java   Source Code and License 6 votes vote down vote up
public void run() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });
        ChannelFuture f = b.connect().sync();
        f.channel().closeFuture().sync();

    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 13
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 14
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 15
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 16
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 17
Project: AlphaLibary   File: EchoClient.java   Source Code and License 6 votes vote down vote up
public EchoClient(String host, int port) {
    EventLoopGroup worker = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();

    b.group(worker)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    socketChannel.pipeline()
                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(ech);
                }
            });

    b.connect(host, port);
}
 
Example 18
Project: fresco_floodlight   File: RemoteSyncManager.java   Source Code and License 6 votes vote down vote up
@Override
public void startUp(FloodlightModuleContext context) 
        throws FloodlightModuleException {
    shutdown = false;
    workerExecutor = new NioEventLoopGroup();
    timer = new HashedWheelTimer();
    
    pipelineFactory = new RemoteSyncChannelInitializer(timer, this);
    
    final Bootstrap bootstrap = new Bootstrap()
    .channel(NioSocketChannel.class)
    .group(workerExecutor)
    .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)
    .handler(pipelineFactory);
    
    clientBootstrap = bootstrap;
}
 
Example 19
Project: ditb   File: AsyncRpcClient.java   Source Code and License 6 votes vote down vote up
private static Pair<EventLoopGroup, Class<? extends Channel>> createEventLoopGroup(
    Configuration conf) {
  // Max amount of threads to use. 0 lets Netty decide based on amount of cores
  int maxThreads = conf.getInt(CLIENT_MAX_THREADS, 0);

  // Config to enable native transport. Does not seem to be stable at time of implementation
  // although it is not extensively tested.
  boolean epollEnabled = conf.getBoolean(USE_NATIVE_TRANSPORT, false);

  // Use the faster native epoll transport mechanism on linux if enabled
  if (epollEnabled && JVM.isLinux() && JVM.isAmd64()) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Create EpollEventLoopGroup with maxThreads = " + maxThreads);
    }
    return new Pair<EventLoopGroup, Class<? extends Channel>>(new EpollEventLoopGroup(maxThreads,
        Threads.newDaemonThreadFactory("AsyncRpcChannel")), EpollSocketChannel.class);
  } else {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Create NioEventLoopGroup with maxThreads = " + maxThreads);
    }
    return new Pair<EventLoopGroup, Class<? extends Channel>>(new NioEventLoopGroup(maxThreads,
        Threads.newDaemonThreadFactory("AsyncRpcChannel")), NioSocketChannel.class);
  }
}
 
Example 20
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 21
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 22
Project: JPRE   File: TestClient.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception {
	EventLoopGroup group = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress(new InetSocketAddress(this.host, this.port))
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						System.out.println("connected server...");
						ch.pipeline().addLast(new ByteArrayEncoder());
						ch.pipeline().addLast(new ByteArrayDecoder());
						ch.pipeline().addLast(new EchoClientHandler());
					}
				});

		ChannelFuture cf = b.connect().sync();

		cf.channel().closeFuture().sync();
	} finally {
		group.shutdownGracefully().sync();
	}
}
 
Example 23
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 24
Project: aws-sdk-java-v2   File: SocketChannelResolver.java   Source Code and License 6 votes vote down vote up
/**
 * Attempts to determine the {@link Channel} class that corresponds to the given
 * event loop group.
 *
 * @param eventLoopGroup the event loop group to determine the {@link Channel} for
 * @return A {@link Channel} class for the given event loop group.
 */
public static Class<? extends Channel> resolveSocketChannelClass(EventLoopGroup eventLoopGroup) {
    if (eventLoopGroup instanceof DelegatingEventLoopGroup) {
        return resolveSocketChannelClass(((DelegatingEventLoopGroup) eventLoopGroup).getDelegate());
    }
    if (eventLoopGroup instanceof NioEventLoopGroup) {
        return NioSocketChannel.class;
    }
    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        return EpollSocketChannel.class;
    }
    String socketFqcn = KNOWN_EL_GROUPS.get(eventLoopGroup.getClass().getName());
    if (socketFqcn == null) {
        throw new IllegalArgumentException("Unknown event loop group : " + eventLoopGroup.getClass());
    }
    return invokeSafely(() -> (Class<? extends Channel>) Class.forName(socketFqcn));
}
 
Example 25
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 26
Project: tcp-gateway   File: TcpClient.java   Source Code and License 6 votes vote down vote up
/**
 * Init Bootstrap
 */
public static final Bootstrap getBootstrap() {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
            pipeline.addLast("decoder", new ProtobufDecoder(MessageBuf.JMTransfer.getDefaultInstance()));
            pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
            pipeline.addLast("encoder", new ProtobufEncoder());
            pipeline.addLast("handler", new TcpClientHandler());
        }
    });


    b.option(ChannelOption.SO_KEEPALIVE, true);
    return b;
}
 
Example 27
Project: AppCoins-ethereumj   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 = ctx.getBean(EthereumChannelInitializer.class, 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 28
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 29
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 30
Project: CustomWorldGen   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
 */
@SideOnly(Side.CLIENT)
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 31
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 32
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 33
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 34
Project: os   File: WebSocketServerInitializer.java   Source Code and License 5 votes vote down vote up
protected void initChannel(NioSocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // 编解码 http 请求
    pipeline.addLast(new HttpServerCodec());
    // 写文件内容
    pipeline.addLast(new ChunkedWriteHandler());
    // 聚合解码 HttpRequest/HttpContent/LastHttpContent 到 FullHttpRequest
    // 保证接收的 Http 请求的完整性
    pipeline.addLast(new HttpObjectAggregator(64 * 1024));
    // 处理其他的 WebSocketFrame
    pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));
    // 处理 TextWebSocketFrame
    pipeline.addLast(protoCodec);
    pipeline.addLast(serverHandler);
}
 
Example 35
Project: DNCF   File: DNCNettyClient.java   Source Code and License 5 votes vote down vote up
public void start() throws Exception {
    try {
        logger.info("[info] >>> start netty client.");
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(initializer);
        logger.info("[info] >>> set netty client params");
        bootstrap.option(ChannelOption.SO_BACKLOG, 65535);
        //keep connect
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);


        channel = bootstrap.connect(host, port).syncUninterruptibly().channel();
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("[info] >>> netty client start fail.");
    }
}
 
Example 36
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 37
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 38
Project: dremio-oss   File: TransportCheck.java   Source Code and License 5 votes vote down vote up
public static Class<? extends SocketChannel> getClientSocketChannel(){
  if(SUPPORTS_EPOLL){
    return EpollSocketChannel.class;
  }else{
    return NioSocketChannel.class;
  }
}
 
Example 39
Project: commelina   File: NettyClientTest.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                        pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                        pipeline.addLast(new SimpleClientChannelHandler());
                    }

                });
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
        if (channelFuture.isSuccess()) {
            System.out.println(String.format("connect server(%s:%s) sucess", host, port));
        }
        channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 40
Project: talchain   File: EthereumChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
public void initChannel(NioSocketChannel ch) throws Exception {
    try {
        if (!peerDiscoveryMode) {
            logger.debug("Open {} connection, channel: {}", isInbound() ? "inbound" : "outbound", ch.toString());
        }

        if (isInbound() && channelManager.isRecentlyDisconnected(ch.remoteAddress().getAddress())) {
            // avoid too frequent connection attempts
            logger.debug("Drop connection - the same IP was disconnected recently, channel: {}", ch.toString());
            ch.disconnect();
            return;
        }

        final org.talchain.net.server.Channel channel = ctx.getBean(org.talchain.net.server.Channel.class);
        channel.init(ch.pipeline(), remoteId, peerDiscoveryMode, channelManager);

        if(!peerDiscoveryMode) {
            channelManager.add(channel);
        }

        // limit the size of receiving buffer to 1024
        ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024));
        ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024);
        ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);

        // be aware of channel closing
        ch.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!peerDiscoveryMode) {
                    channelManager.notifyDisconnect(channel);
                }
            }
        });

    } catch (Exception e) {
        logger.error("Unexpected error: ", e);
    }
}
 
Example 41
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 42
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 43
Project: rskj   File: EthereumChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
public void initChannel(NioSocketChannel ch) throws Exception {
    try {
        if (!peerDiscoveryMode) {
            logger.info("Open {} connection, channel: {}", isInbound() ? "inbound" : "outbound", ch.toString());
        }

        if (isInbound() && channelManager.isRecentlyDisconnected(ch.remoteAddress().getAddress())) {
            // avoid too frequent connection attempts
            logger.info("Drop connection - the same IP was disconnected recently, channel: {}", ch.toString());
            ch.disconnect();
            return;
        }

        final Channel channel = channelFactory.newInstance();
        channel.init(ch.pipeline(), remoteId, peerDiscoveryMode);

        if(!peerDiscoveryMode) {
            channelManager.add(channel);
        }

        // limit the size of receiving buffer to 1024
        ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(16_777_216));
        ch.config().setOption(ChannelOption.SO_RCVBUF, 16_777_216);
        ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);

        // be aware of channel closing
        ch.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!peerDiscoveryMode) {
                    channelManager.notifyDisconnect(channel);
                }
            }
        });

    } catch (Exception e) {
        logger.error("Unexpected error: ", e);
    }
}
 
Example 44
Project: ClusterDeviceControlPlatform   File: ServerChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
protected void initChannel(NioSocketChannel ch) {
    ch.pipeline().addLast(new LoggingHandler("kyOutlineLogger", LogLevel.INFO));
    ch.pipeline().addLast(configHandler);
    ch.pipeline().addLast(canFrameChannelInboundHandler);
    ch.pipeline().addLast(parsedMessageInBoundHandler);
    ch.pipeline().addLast(sendingOutBoundHandler);
}
 
Example 45
Project: ClusterDeviceControlPlatform   File: ServerChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
    ch.pipeline().addLast(configHandler);
    ch.pipeline().addLast(new LoggingHandler("kyOutlineLogger", LogLevel.INFO));
    ch.pipeline().addLast(frameRecognitionInBoundHandler);
    ch.pipeline().addLast(parsedMessageInBoundHandler);
    ch.pipeline().addLast(recognitionOutBoundHandler);
}
 
Example 46
Project: ClusterDeviceControlPlatform   File: ClientChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
    ch.pipeline().addLast(new LoggingHandler("kyOutlineLogger", LogLevel.INFO));
    ch.pipeline().addLast(configHandler);
    ch.pipeline().addLast(frameRecognitionInBoundHandler);
    ch.pipeline().addLast(parsedMessageInBoundHandler);
    ch.pipeline().addLast(recognitionOutBoundHandler);
}
 
Example 47
Project: elephant   File: NettyRemotingClient.java   Source Code and License 5 votes vote down vote up
@Override
public void start() {
	this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyClientConfig.getClientWorkerThreads(),new ThreadFactory() {
		private AtomicInteger threadIndex = new AtomicInteger(0);
		@Override
		public Thread newThread(Runnable r) {
			return new Thread(r, "NettyClientWorkerThread_"	+ this.threadIndex.incrementAndGet());
		}
	});
	this.bootstrap
			.group(this.eventLoopGroupWorker)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.option(ChannelOption.SO_KEEPALIVE, false)
			.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,nettyClientConfig.getConnectTimeoutMillis())
			.option(ChannelOption.SO_SNDBUF,nettyClientConfig.getClientSocketSndBufSize())
			.option(ChannelOption.SO_RCVBUF,nettyClientConfig.getClientSocketRcvBufSize())
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					// 编码
					ch.pipeline().addLast(new NettyEncoder(serializeTypeCurrentRPC));
					// 解码
					ch.pipeline().addLast(new NettyDecoder(RemotingCommand.class,serializeTypeCurrentRPC));
					// 心跳
					ch.pipeline().addLast(new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()));
					// 业务处理
					ch.pipeline().addLast(defaultEventExecutorGroup,new NettyConnectManageHandler(), new NettyClientHandler());
				}
			});
}
 
Example 48
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 49
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 50
Project: BaseClient   File: NetworkManager.java   Source Code and License 5 votes vote down vote up
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    Class <? extends SocketChannel > oclass;
    LazyLoadBase <? extends EventLoopGroup > lazyloadbase;

    if (Epoll.isAvailable() && p_181124_2_)
    {
        oclass = EpollSocketChannel.class;
        lazyloadbase = field_181125_e;
    }
    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 MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
        }
    })).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
    return networkmanager;
}
 
Example 51
Project: BaseClient   File: NetworkManager.java   Source Code and License 5 votes vote down vote up
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    Class <? extends SocketChannel > oclass;
    LazyLoadBase <? extends EventLoopGroup > lazyloadbase;

    if (Epoll.isAvailable() && p_181124_2_)
    {
        oclass = EpollSocketChannel.class;
        lazyloadbase = field_181125_e;
    }
    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 MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
        }
    })).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
    return networkmanager;
}
 
Example 52
Project: netty_op   File: ErrorTimeClient.java   Source Code and License 5 votes vote down vote up
/**
 *@description 连接服务器
 *@time 创建时间:2017年7月21日下午4:15:50
 *@param host
 *@param port
 *@throws InterruptedException
 *@author dzn
 */
public void connect(String host, int port) throws InterruptedException{
    EventLoopGroup group = new NioEventLoopGroup();
    try{
        
        //netty客户端
        Bootstrap boot = new Bootstrap();
        boot.group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
            
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //对输入数据进行业务逻辑处理
                ch.pipeline().addLast(new ErrorTimeClientHandler());
            }
            
        });
        
        //使用netty客户端连接netty服务器
        ChannelFuture future = boot.connect(host, port).sync();
        
        //等待客户端Channel关闭
        future.channel().closeFuture().sync();
        
    }finally{
        group.shutdownGracefully();
    }
}
 
Example 53
Project: netty_op   File: RightTimeClient.java   Source Code and License 5 votes vote down vote up
/**
 *@description 连接服务器
 *@time 创建时间:2017年7月21日下午4:15:50
 *@param host
 *@param port
 *@throws InterruptedException
 *@author dzn
 */
public void connect(String host, int port) throws InterruptedException{
    EventLoopGroup group = new NioEventLoopGroup();
    try{
        Bootstrap boot = new Bootstrap();
        boot.group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
            
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //增加以\n 和 \r\n为数据换行符的Handler
                ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                //增加字符串解析器
                ch.pipeline().addLast(new StringDecoder());
                //对输入数据进行业务逻辑处理
                ch.pipeline().addLast(new RightTimeClientHandler());
            }
            
        });
        
        //连接服务器
        ChannelFuture future = boot.connect(host, port).sync();
        
        //等待客户端Channel关闭
        future.channel().closeFuture().sync();
        
    }finally{
        group.shutdownGracefully();
    }
}
 
Example 54
Project: QDrill   File: TransportCheck.java   Source Code and License 5 votes vote down vote up
public static Class<? extends SocketChannel> getClientSocketChannel(){
  if(SUPPORTS_EPOLL){
    return EpollSocketChannel.class;
  }else{
    return NioSocketChannel.class;
  }
}
 
Example 55
Project: L2J-Global   File: LoginServerNetworkManager.java   Source Code and License 5 votes vote down vote up
public LoginServerNetworkManager()
{
	//@formatter:off
	_bootstrap = new Bootstrap()
		.group(EventLoopGroupManager.getInstance().getWorkerGroup())
		.channel(NioSocketChannel.class)
		.option(ChannelOption.SO_KEEPALIVE, true)
		.handler(new LoginServerInitializer());
	//@formatter:on
}
 
Example 56
Project: candlelight   File: NetworkEngine.java   Source Code and License 5 votes vote down vote up
public NetworkDispatcher connectToPublic(InetAddress address, int port)
{
	NetworkDispatcher dispatch = new NetworkDispatcher(this, NetworkSide.CLIENT);

	final EventLoopGroup boss = new NioEventLoopGroup();
	final Bootstrap b = new Bootstrap()
			.group(boss)
			.handler(new ChannelInitializer<Channel>() {
				@Override
				protected void initChannel(Channel ch) throws Exception
				{
					final PacketRegistry registry = NetworkEngine.this.packetRegistry;

					ch.pipeline()
							.addLast(new VarInt21FrameDecoder())
							.addLast(new PacketDecoder(NetworkSide.CLIENT,
									registry))
							.addLast(new VarInt21FrameEncoder())
							.addLast(new PacketEncoder(NetworkSide.SERVER,
									registry))
							.addLast(dispatch);
				}
			})
			.channel(NioSocketChannel.class);

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

	return dispatch;
}
 
Example 57
Project: candlelight   File: Client.java   Source Code and License 5 votes vote down vote up
@Override
public void run()
{
	System.out.println("Starting Client...");
	EventLoopGroup boss = new NioEventLoopGroup();
	try
	{
		Bootstrap b = new Bootstrap();
		b.group(boss)
				.channel(NioSocketChannel.class)
				.handler(new ClientChannelInitializer());

		System.out.println("Connecting to Server[" + this.host + ":" + this.port + "]...");
		Channel ch = b.connect(this.host, this.port).sync().channel();
		System.out.println("Connection Established!");

		//Process stuff

		ch.closeFuture().sync();
	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
	finally
	{
		System.out.println("Stopping Client...");
		boss.shutdownGracefully();
	}

	System.out.println("Connection Ended!");
}
 
Example 58
Project: rpc   File: NettyClient.java   Source Code and License 5 votes vote down vote up
private void init() throws InterruptedException {
    b = new Bootstrap();
    group = new NioEventLoopGroup(2);
    b.group(group)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    initClientChannel(ch);
                }
            });
    connect();
}
 
Example 59
Project: spark_deep   File: NettyUtils.java   Source Code and License 5 votes vote down vote up
/** Returns the correct (client) SocketChannel class based on IOMode. */
public static Class<? extends Channel> getClientChannelClass(IOMode mode) {
  switch (mode) {
    case NIO:
      return NioSocketChannel.class;
    case EPOLL:
      return EpollSocketChannel.class;
    default:
      throw new IllegalArgumentException("Unknown io mode: " + mode);
  }
}
 
Example 60
Project: spark_deep   File: EchoClient.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .option(ChannelOption.TCP_NODELAY, true)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 if (sslCtx != null) {
                     p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                 }
                // p.addLast(new LoggingHandler(LogLevel.INFO));
                 p.addLast(new EchoClientHandler());
             }
         });

        // 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();
    }
}