io.netty.channel.ChannelOption Java Examples

The following examples show how to use io.netty.channel.ChannelOption. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FastdfsPoolGroup.java    From fastdfs-client with Apache License 2.0 6 votes vote down vote up
@Override
protected FastdfsPool newPool(InetSocketAddress addr) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("channel pool created : {}", addr);
    }

    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(loopGroup);
    bootstrap.remoteAddress(addr);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    return new FastdfsPool(
            bootstrap,
            readTimeout,
            idleTimeout,
            maxConnPerHost,
            maxPendingRequests
    );
}
 
Example #2
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private NettyClientTransport newTransport(ProtocolNegotiator negotiator, int maxMsgSize,
    int maxHeaderListSize, String userAgent, boolean enableKeepAlive) {
  long keepAliveTimeNano = KEEPALIVE_TIME_NANOS_DISABLED;
  long keepAliveTimeoutNano = TimeUnit.SECONDS.toNanos(1L);
  if (enableKeepAlive) {
    keepAliveTimeNano = TimeUnit.SECONDS.toNanos(10L);
  }
  NettyClientTransport transport = new NettyClientTransport(
      address, NioSocketChannel.class, new HashMap<ChannelOption<?>, Object>(), group, negotiator,
      DEFAULT_WINDOW_SIZE, maxMsgSize, maxHeaderListSize,
      keepAliveTimeNano, keepAliveTimeoutNano,
      false, authority, userAgent, tooManyPingsRunnable,
      new TransportTracer(), eagAttributes, new SocketPicker());
  transports.add(transport);
  return transport;
}
 
Example #3
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private void startServer(int maxStreamsPerConnection, int maxHeaderListSize) throws IOException {
  server = new NettyServer(
      TestUtils.testServerAddress(0),
      NioServerSocketChannel.class,
      new HashMap<ChannelOption<?>, Object>(),
      group, group, negotiator,
      Collections.<ServerStreamTracer.Factory>emptyList(),
      TransportTracer.getDefaultFactory(),
      maxStreamsPerConnection,
      DEFAULT_WINDOW_SIZE, DEFAULT_MAX_MESSAGE_SIZE, maxHeaderListSize,
      DEFAULT_SERVER_KEEPALIVE_TIME_NANOS, DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS,
      MAX_CONNECTION_IDLE_NANOS_DISABLED,
      MAX_CONNECTION_AGE_NANOS_DISABLED, MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE, true, 0,
      channelz);
  server.start(serverListener);
  address = TestUtils.testServerAddress(server.getPort());
  authority = GrpcUtil.authorityFromHostAndPort(address.getHostString(), address.getPort());
}
 
Example #4
Source File: NettyRestServer.java    From netty-restful-server with MIT License 6 votes vote down vote up
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ServerInitializer());

        Channel ch = b.bind(Config.getInt("server.port")).sync().channel();

        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #5
Source File: NettyTransport.java    From jzab with Apache License 2.0 6 votes vote down vote up
public Sender(final String source, final String destination) {
  this.destination = destination;
  bootstrap = new Bootstrap();
  bootstrap.group(workerGroup);
  bootstrap.channel(NioSocketChannel.class);
  bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
  bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
  bootstrap.option(ChannelOption.TCP_NODELAY, true);
  bootstrap.handler(new ChannelInitializer<SocketChannel>() {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
      if (isSslEnabled()) {
        SSLEngine engine = serverContext.createSSLEngine();
        engine.setUseClientMode(true);
        ch.pipeline().addLast(new SslHandler(engine));
      }
      // Inbound handlers.
      ch.pipeline().addLast("clientError", new ClientErrorHandler());
      // Outbound handlers.
      ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
    }
  });
}
 
Example #6
Source File: BaseServer.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
private void buildServerAndRun(EventLoopGroup bossGroup, EventLoopGroup workerGroup,
                               Class<? extends ServerChannel> channelClass) throws Exception {

    var b = new ServerBootstrap();
    try {
        b.group(bossGroup, workerGroup)
                .channel(channelClass)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(getChannelInitializer());

        var listenTo = (listenAddress == null || listenAddress.isEmpty())
                ? new InetSocketAddress(port)
                : new InetSocketAddress(listenAddress, port);
        this.cf = b.bind(listenTo).sync();
    } catch (Exception e) {
        log.error("Error initializing {}, port {}", getServerName(), port, e);
        throw e;
    }

    log.info("{} server listening at {} port.", getServerName(), port);
}
 
Example #7
Source File: SimpleSctpServer.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {       
    EventLoopGroup mainLoop = new NioEventLoopGroup(1);
    EventLoopGroup workerLoop = new NioEventLoopGroup();
    try {
    	ChannelFuture f = new ServerBootstrap().group(mainLoop, workerLoop)
         .channel(NioSctpServerChannel.class)
         .option(ChannelOption.SO_BACKLOG, 100)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new ChannelInitializer<SctpChannel>() {
             @Override
             public void initChannel(SctpChannel ch) throws Exception {
            	 ChannelPipeline p = ch.pipeline();                	
                 p.addLast(new SimpleSctpServerHandler());
             }
         }).bind(PORT).sync();            
        f.channel().closeFuture().sync();
    } finally {            
        mainLoop.shutdownGracefully();
        workerLoop.shutdownGracefully();
    }
}
 
Example #8
Source File: HexDumpProxyFrontendHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop())
     .channel(ctx.channel().getClass())
     .handler(new HexDumpProxyBackendHandler(inboundChannel))
     .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}
 
Example #9
Source File: MySQLClient.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to MySQL.
 */
public synchronized void connect() {
    responseCallback = new DefaultPromise<>(eventLoopGroup.next());
    channel = new Bootstrap()
            .group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(final SocketChannel socketChannel) {
                    socketChannel.pipeline().addLast(new PacketCodec(new MySQLPacketCodecEngine()));
                    socketChannel.pipeline().addLast(new MySQLCommandPacketDecoder());
                    socketChannel.pipeline().addLast(new MySQLNegotiateHandler(username, password, responseCallback));
                    socketChannel.pipeline().addLast(new MySQLCommandResponseHandler());
                }
            })
            .option(ChannelOption.AUTO_READ, true)
            .connect(host, port).channel();
    serverInfo = waitExpectedResponse(ServerInfo.class);
}
 
Example #10
Source File: ServerBootstrap.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
ServerBootstrapAcceptor(
        EventLoopGroup childGroup, ChannelHandler childHandler,
        Entry<ChannelOption<?>, Object>[] childOptions, Entry<AttributeKey<?>, Object>[] childAttrs,

        // IRIS UPDATE
        RateLimiter acceptRateLimiter, NetworkClock acceptNetworkClock
        // END IRIS UPDATE
        
        ) {
    this.childGroup = childGroup;
    this.childHandler = childHandler;
    this.childOptions = childOptions;
    this.childAttrs = childAttrs;

    // IRIS UPDATE
    this.acceptRateLimiter = acceptRateLimiter;
    this.acceptNetworkClock = acceptNetworkClock;
    // END IRIS UPDATE
}
 
Example #11
Source File: NettyServerB.java    From tutorials with MIT License 6 votes vote down vote up
private void run() throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB());
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = b.bind(port).sync(); // (7)
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
 
Example #12
Source File: MixServer.java    From incubator-hivemall with Apache License 2.0 6 votes vote down vote up
private void acceptConnections(@Nonnull MixServerInitializer initializer, int port,
        @Nonnegative int numWorkers) throws InterruptedException {
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup(numWorkers);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(initializer);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync();
        this.state = ServerState.RUNNING;

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        this.state = ServerState.STOPPING;
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example #13
Source File: AbstractNettyClient.java    From qmq with Apache License 2.0 6 votes vote down vote up
public synchronized void start(NettyClientConfig config) {
    if (started.get()) {
        return;
    }
    initHandler();
    Bootstrap bootstrap = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(clientName + "-boss"));
    eventExecutors = new DefaultEventExecutorGroup(config.getClientWorkerThreads(), new DefaultThreadFactory(clientName + "-worker"));
    connectManager = new NettyConnectManageHandler(bootstrap, config.getConnectTimeoutMillis());
    bootstrap.group(this.eventLoopGroup)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeoutMillis())
            .option(ChannelOption.SO_SNDBUF, config.getClientSocketSndBufSize())
            .option(ChannelOption.SO_RCVBUF, config.getClientSocketRcvBufSize())
            .handler(newChannelInitializer(config, eventExecutors, connectManager));
    started.set(true);
}
 
Example #14
Source File: Client.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void run() throws Exception {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap(); // (2)
        b.group(workerGroup)
                .channel(NioSocketChannel.class) // (3)
                .handler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(clientHandler);

                    }
                })
                .option(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.connect("localhost", port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
 
Example #15
Source File: SynapseClient.java    From Nemisys with GNU General Public License v3.0 6 votes vote down vote up
public boolean connect() {
    clientGroup = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();  //服务引导程序,服务器端快速启动程序
        b.group(clientGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new SynapseClientInitializer(this));

        b.connect(this.interfaz, this.port).get();
        // 等待服务端监听端口关闭,等待服务端链路关闭之后main函数才退出
        //future.channel().closeFuture().sync();
        return true;
    } catch (Exception e) {
        Server.getInstance().getLogger().alert("Synapse Client can't connect to server: " + this.interfaz + ":" + this.port);
        Server.getInstance().getLogger().alert("Reason: " + e.getLocalizedMessage());
        Server.getInstance().getLogger().warning("We will reconnect in 3 seconds");
        this.reconnect();
        return false;
    }
}
 
Example #16
Source File: NettyMessagingService.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Bootstraps a server.
 *
 * @return a future to be completed once the server has been bound to all interfaces
 */
private CompletableFuture<Void> bootstrapServer() {
  ServerBootstrap b = new ServerBootstrap();
  b.option(ChannelOption.SO_REUSEADDR, true);
  b.option(ChannelOption.SO_BACKLOG, 128);
  b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
      new WriteBufferWaterMark(8 * 1024, 32 * 1024));
  b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024);
  b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024);
  b.childOption(ChannelOption.SO_KEEPALIVE, true);
  b.childOption(ChannelOption.TCP_NODELAY, true);
  b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
  b.group(serverGroup, clientGroup);
  b.channel(serverChannelClass);
  if (enableNettyTls) {
    try {
      b.childHandler(new SslServerChannelInitializer());
    } catch (SSLException e) {
      return Futures.exceptionalFuture(e);
    }
  } else {
    b.childHandler(new BasicServerChannelInitializer());
  }
  return bind(b);
}
 
Example #17
Source File: DefaultSctpChannelConfig.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public <T> boolean setOption(ChannelOption<T> option, T value) {
    validate(option, value);

    if (option == SO_RCVBUF) {
        setReceiveBufferSize((Integer) value);
    } else if (option == SO_SNDBUF) {
        setSendBufferSize((Integer) value);
    } else if (option == SCTP_NODELAY) {
        setSctpNoDelay((Boolean) value);
    } else if (option == SCTP_INIT_MAXSTREAMS) {
        setInitMaxStreams((SctpStandardSocketOptions.InitMaxStreams) value);
    } else {
        return super.setOption(option, value);
    }

    return true;
}
 
Example #18
Source File: Bootstrap.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
void init(Channel channel) throws Exception {
    ChannelPipeline p = channel.pipeline();
    p.addLast(config.handler());

    final Map<ChannelOption<?>, Object> options = options0();
    synchronized (options) {
        setChannelOptions(channel, options, logger);
    }

    final Map<AttributeKey<?>, Object> attrs = attrs0();
    synchronized (attrs) {
        for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
            channel.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
        }
    }
}
 
Example #19
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example #20
Source File: KQueueSocketChannelConfig.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public Map<ChannelOption<?>, Object> getOptions() {
    return getOptions(
            super.getOptions(),
            SO_RCVBUF, SO_SNDBUF, TCP_NODELAY, SO_KEEPALIVE, SO_REUSEADDR, SO_LINGER, IP_TOS,
            ALLOW_HALF_CLOSURE, SO_SNDLOWAT, TCP_NOPUSH);
}
 
Example #21
Source File: HttpXmlClient.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void connect(int port) throws Exception {
    // 配置客户端NIO线程组
    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 {
                        ch.pipeline().addLast("http-decoder",
                                new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator",
                                new HttpObjectAggregator(65536));
                        // XML解码器
                        ch.pipeline().addLast(
                                "xml-decoder",
                                new HttpXmlResponseDecoder(Order.class,
                                        true));
                        ch.pipeline().addLast("http-encoder",
                                new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder",
                                new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler",
                                new HttpXmlClientHandler());
                    }
                });

        // 发起异步连接操作
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 当代客户端链路关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
 
Example #22
Source File: TransportConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Default TransportConfig with options
 */
protected TransportConfig(Map<ChannelOption<?>, ?> options) {
	this.attrs = Collections.emptyMap();
	this.doOnChannelInit = ChannelPipelineConfigurer.emptyConfigurer();
	this.observer = ConnectionObserver.emptyListener();
	this.options = Objects.requireNonNull(options, "options");
	this.preferNative = LoopResources.DEFAULT_NATIVE;
}
 
Example #23
Source File: DefaultDatagramChannelConfig.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked", "deprecation" })
public <T> T getOption(ChannelOption<T> option) {
    if (option == SO_BROADCAST) {
        return (T) Boolean.valueOf(isBroadcast());
    }
    if (option == SO_RCVBUF) {
        return (T) Integer.valueOf(getReceiveBufferSize());
    }
    if (option == SO_SNDBUF) {
        return (T) Integer.valueOf(getSendBufferSize());
    }
    if (option == SO_REUSEADDR) {
        return (T) Boolean.valueOf(isReuseAddress());
    }
    if (option == IP_MULTICAST_LOOP_DISABLED) {
        return (T) Boolean.valueOf(isLoopbackModeDisabled());
    }
    if (option == IP_MULTICAST_ADDR) {
        return (T) getInterface();
    }
    if (option == IP_MULTICAST_IF) {
        return (T) getNetworkInterface();
    }
    if (option == IP_MULTICAST_TTL) {
        return (T) Integer.valueOf(getTimeToLive());
    }
    if (option == IP_TOS) {
        return (T) Integer.valueOf(getTrafficClass());
    }
    if (option == DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) {
        return (T) Boolean.valueOf(activeOnOpen);
    }
    return super.getOption(option);
}
 
Example #24
Source File: DefaultClientPool.java    From protools with Apache License 2.0 5 votes vote down vote up
private void init(String url, int maxCount) throws URISyntaxException, SSLException {
    URI uri = new URI(url);
    if (uri.getScheme() == null || uri.getHost() == null) {
        throw new IllegalArgumentException("uri不合法");
    }
    scheme = uri.getScheme();
    host = uri.getHost();
    port = uri.getPort();
    if (port == -1) {
        if (HttpScheme.HTTP.equalsIgnoreCase(scheme)) {
            port = 80;
        } else if (HttpScheme.HTTPS.equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!HttpScheme.HTTP.equalsIgnoreCase(scheme) && !HttpScheme.HTTPS.equalsIgnoreCase(scheme)) {
        if (log.isErrorEnabled()) {
            log.error("仅有HTTP(S)是支持的。");
        }
        return;
    }

    final boolean ssl = HttpScheme.HTTPS.equalsIgnoreCase(scheme);

    this.setSSlContext(ssl);

    final Bootstrap b = new Bootstrap();
    b.group(GROUP)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .remoteAddress(InetSocketAddress.createUnresolved(host, port))
    ;

    channelPool = new FixedChannelPool(b, new HttpClientChannelPoolHandler(sslContext), maxCount);
}
 
Example #25
Source File: NettyTelnetServer.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
public void open() throws InterruptedException {
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
        .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new NettyTelnetInitializer());
    channel = serverBootstrap.bind(port).sync().channel();
}
 
Example #26
Source File: SocketConnectionAttemptTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public void testConnectTimeout(Bootstrap cb) throws Throwable {
    cb.handler(new TestHandler()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
    ChannelFuture future = cb.connect(BAD_HOST, BAD_PORT);
    try {
        assertThat(future.await(3000), is(true));
    } finally {
        future.channel().close();
    }
}
 
Example #27
Source File: AvatarMQBrokerServer.java    From AvatarMQ with Apache License 2.0 5 votes vote down vote up
public void init() {
    try {
        handler = new MessageBrokerHandler().buildConsumerHook(new ConsumerMessageHook()).buildProducerHook(new ProducerMessageHook());

        boss = new NioEventLoopGroup(1, threadBossFactory);

        workers = new NioEventLoopGroup(parallel, threadWorkerFactory, NettyUtil.getNioSelectorProvider());

        KryoCodecUtil util = new KryoCodecUtil(KryoPoolFactory.getKryoPoolInstance());

        bootstrap = new ServerBootstrap();

        bootstrap.group(boss, workers).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, false)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_SNDBUF, nettyClustersConfig.getClientSocketSndBufSize())
                .option(ChannelOption.SO_RCVBUF, nettyClustersConfig.getClientSocketRcvBufSize())
                .handler(new LoggingHandler(LogLevel.INFO))
                .localAddress(serverIpAddr)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel ch)
                            throws Exception {
                        ch.pipeline().addLast(
                                defaultEventExecutorGroup,
                                new MessageObjectEncoder(util),
                                new MessageObjectDecoder(util),
                                handler);
                    }
                });

        super.init();
    } catch (IOException ex) {
        Logger.getLogger(AvatarMQBrokerServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #28
Source File: MqttServer.java    From lannister with Apache License 2.0 5 votes vote down vote up
private void executeBootstrap(ScheduledExecutor scheduledExecutor, int port, boolean useWebSocket, boolean useSsl)
		throws InterruptedException {
	ServerBootstrap bootstrap = new ServerBootstrap();

	Class<? extends ServerChannel> serverChannelClass;

	if (Literals.NETTY_EPOLL.equals(Settings.INSTANCE.nettyTransportMode())) {
		serverChannelClass = EpollServerSocketChannel.class;
	}
	else {
		serverChannelClass = NioServerSocketChannel.class;
	}

	bootstrap = bootstrap.group(bossGroup, workerGroup).channel(serverChannelClass);
	bootstrap.option(ChannelOption.TCP_NODELAY, true);

	if (scheduledExecutor != null) {
		bootstrap.handler(scheduledExecutor);
	}

	bootstrap.childHandler(new MqttChannelInitializer(useWebSocket, useSsl));

	bootstrap.childOption(ChannelOption.TCP_NODELAY, true)
			// setting buffer size can improve I/O
			.childOption(ChannelOption.SO_SNDBUF, 1048576).childOption(ChannelOption.SO_RCVBUF, 1048576)
			// recommended in
			// http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#11.0
			.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024))
			.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

	bootstrap.bind(port).sync();
}
 
Example #29
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example #30
Source File: GrpcClient.java    From rapid with Apache License 2.0 5 votes vote down vote up
private Channel getChannel(final Endpoint remote) {
    // TODO: allow configuring SSL/TLS
    Channel channel;
    LOG.debug("Creating channel from {} to {}", address, remote);

    if (settings.getUseInProcessTransport()) {
        channel = InProcessChannelBuilder
                .forName(remote.toString())
                .executor(grpcExecutor)
                .usePlaintext(true)
                .idleTimeout(10, TimeUnit.SECONDS)
                .build();
    } else {
        channel = NettyChannelBuilder
                .forAddress(remote.getHostname().toStringUtf8(), remote.getPort())
                .executor(grpcExecutor)
                .eventLoopGroup(eventLoopGroup)
                .usePlaintext(true)
                .idleTimeout(10, TimeUnit.SECONDS)
                .withOption(ChannelOption.SO_REUSEADDR, true)
                .withOption(ChannelOption.SO_SNDBUF, DEFAULT_BUF_SIZE)
                .withOption(ChannelOption.SO_RCVBUF, DEFAULT_BUF_SIZE)
                .build();
    }

    return channel;
}