io.netty.channel.EventLoopGroup Java Examples

The following examples show how to use io.netty.channel.EventLoopGroup. 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: HttpCorsServer.java    From HttpProxy with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HttpCorsServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #2
Source File: EpollEchoServer.java    From netty.book.kor with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new EpollEventLoopGroup(1);
    EventLoopGroup workerGroup = new EpollEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(EpollServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoServerHandler());
            }
        });

        ChannelFuture f = b.bind(8888).sync();

        f.channel().closeFuture().sync();
    }
    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example #3
Source File: NettyOioServer.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void server(int port) throws Exception {
	final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8")));
	EventLoopGroup group = new OioEventLoopGroup();
	try {
		ServerBootstrap b = new ServerBootstrap();
		b.group(group).channel(OioServerSocketChannel.class).localAddress(new InetSocketAddress(port))
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
							@Override
							public void channelActive(ChannelHandlerContext ctx) throws Exception {
								ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
							}
						});
					}
				});
		ChannelFuture f = b.bind().sync();
		f.channel().closeFuture().sync();
	} finally {
		group.shutdownGracefully().sync();
	}
}
 
Example #4
Source File: UserServer.java    From Bats with Apache License 2.0 6 votes vote down vote up
public UserServer(BootStrapContext context, BufferAllocator allocator, EventLoopGroup eventLoopGroup,
                  UserWorker worker) throws DrillbitStartupException {
  super(UserRpcConfig.getMapping(context.getConfig(), context.getExecutor()),
      allocator.getAsByteBufAllocator(),
      eventLoopGroup);
  this.config = new UserConnectionConfig(allocator, context, new UserServerRequestHandler(worker));
  this.sslChannel = null;
  try {
    this.sslConfig = new SSLConfigBuilder()
        .config(context.getConfig())
        .mode(SSLConfig.Mode.SERVER)
        .initializeSSLContext(true)
        .validateKeyStore(true)
        .build();
  } catch (DrillException e) {
    throw new DrillbitStartupException(e.getMessage(), e.getCause());
  }
  this.userWorker = worker;

  // Initialize Singleton instance of UserRpcMetrics.
  ((UserRpcMetrics)UserRpcMetrics.getInstance()).initialize(config.isEncryptionEnabled(), allocator);
}
 
Example #5
Source File: TcpRttServer.java    From kcp-netty with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new TcpRttDecoder())
                                .addLast(new TcpRttServerHandler());
                    }
                }).childOption(ChannelOption.TCP_NODELAY, true);

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        group.shutdownGracefully();
    }
}
 
Example #6
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void newClientBootstrap(String host, int port, ChannelInitializer<SocketChannel> initializer){
	EventLoopGroup group = new NioEventLoopGroup();
       try {
           Bootstrap b = new Bootstrap();
           ChannelFuture f = b.group(group)
           		.channel(NioSocketChannel.class)
           		.option(ChannelOption.SO_KEEPALIVE, true)
           		.handler(new LoggingHandler(LogLevel.INFO))
           		.handler(initializer)
           		.connect(host, port).sync();            
           f.channel().closeFuture().sync();            
       } catch (Exception e){   
           e.printStackTrace();
       } finally {        	
           group.shutdownGracefully();
       }
}
 
Example #7
Source File: TelnetServer.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new TelnetServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #8
Source File: NettyClient.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = 8080;
    EventLoopGroup 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 {
                ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(), new ClientHandler());
            }
        });

        ChannelFuture f = b.connect(host, port).sync();

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
 
Example #9
Source File: BridgeServer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public BridgeServer(
      BridgeServerConfig serverConfig,
      InetSocketAddress socketBindAddress,
      ChannelInitializer<SocketChannel> channelInitializer,
      EventLoopGroup bossGroup,
      EventLoopGroup workerGroup,
      Map<ChannelOption<?>, Object> childChannelOptions,
      Map<ChannelOption<?>, Object> parentChannelOptions,
      BridgeServerEventLoopProvider eventLoopProvider
) {
   this.runner = new ServerRunner(
         serverConfig,
         socketBindAddress,
         channelInitializer,
         bossGroup,
         workerGroup,
         childChannelOptions,
         parentChannelOptions,
         eventLoopProvider
   );
}
 
Example #10
Source File: EchoServerV1.java    From netty.book.kor with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoServerV1Handler());
            }
        });

        ChannelFuture f = b.bind(8888).sync();
        f.channel().closeFuture().sync();
    }
    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example #11
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 #12
Source File: Server.java    From heroic with Apache License 2.0 6 votes vote down vote up
static AsyncFuture<Server> setup(
    final AsyncFramework async, final CollectdChannelHandler handler, final InetAddress host,
    final int port
) {
    final EventLoopGroup group = new NioEventLoopGroup();
    final Bootstrap b = new Bootstrap();

    b
        .group(group)
        .channel(NioDatagramChannel.class)
        .option(ChannelOption.SO_BROADCAST, true)
        .handler(handler);

    final ResolvableFuture<Server> future = async.future();

    b.bind(host, port).addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            future.resolve(new Server(async, f.channel()));
        } else {
            future.fail(
                f.cause() != null ? f.cause() : new RuntimeException("Failed to bind"));
        }
    });

    return future;
}
 
Example #13
Source File: SecureChatServer.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextGMBuilder.forServer(ENC_CERT, ENC_KEY, SIGN_CERT, SIGN_KEY, null)
            /* 默认协商出来的是ECDHE_SM4_SM3算法,所以必须是双向SSL,并且客户端和服务端必须要有加密证书和签名证书 */
            .clientAuth(ClientAuth.REQUIRE)
            .build();

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new SecureChatServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #14
Source File: EchoTest.java    From jdk-source-analysis with Apache License 2.0 6 votes vote down vote up
@Test
public void testServer() throws InterruptedException {
  EchoServerHandler serverHandler = new EchoServerHandler();
  EventLoopGroup bossGroup = new NioEventLoopGroup();
  EventLoopGroup wokerGroup = new NioEventLoopGroup();
  try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, wokerGroup)
      .channel(NioServerSocketChannel.class)
      .localAddress(new InetSocketAddress(PORT))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ch.pipeline().addLast(serverHandler);
        }
      });
    ChannelFuture f = b.bind().sync();
    f.channel().closeFuture().sync();
  } finally {
    bossGroup.shutdownGracefully().sync();
    wokerGroup.shutdownGracefully().sync();
  }
}
 
Example #15
Source File: SimpleSctpClient.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {        
    EventLoopGroup loopGroup = new NioEventLoopGroup();
    try {            
    	ChannelFuture f = new Bootstrap().group(loopGroup)
         .channel(NioSctpChannel.class)
         // set SCTP option
         .option(SctpChannelOption.SCTP_NODELAY, true) 
         .handler(new ChannelInitializer<SctpChannel>() {
             @Override
             public void initChannel(SctpChannel ch) throws Exception {
            	 ChannelPipeline p = ch.pipeline();
                 p.addLast(new SimpleSctpClientHandler());
             }
         }).connect(HOST, PORT).sync();            
        f.channel().closeFuture().sync();
    } finally {
    	loopGroup.shutdownGracefully();
    }
}
 
Example #16
Source File: PsyncLatencyTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
private void startGetLatency() {

		EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 
        Bootstrap b = new Bootstrap();
        b.group(eventLoopGroup)
         .channel(NioSocketChannel.class)
         .option(ChannelOption.TCP_NODELAY, true)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 p.addLast(new LoggingHandler(LogLevel.DEBUG));
                 p.addLast(new NettySimpleMessageHandler());
                 p.addLast(new ReceiveMessageHandler(runId, offset));
             }
         });
        b.connect(dest);
	}
 
Example #17
Source File: ChannelConfiguration.java    From xio with Apache License 2.0 6 votes vote down vote up
public static ChannelConfiguration clientConfig(EventLoopGroup workerGroup) {
  EventLoopGroup parent = workerGroup;
  if (parent instanceof EventLoop) {
    parent = ((EventLoop) workerGroup).parent();
  }
  Class<? extends Channel> channelClass;
  if (parent instanceof EpollEventLoopGroup) {
    channelClass = EpollSocketChannel.class;
  } else if (parent instanceof NioEventLoopGroup) {
    channelClass = NioSocketChannel.class;
  } else {
    throw new RuntimeException("Unsupported EventLoopGroup " + workerGroup.getClass());
  }

  return new ChannelConfiguration(workerGroup, channelClass);
}
 
Example #18
Source File: NettyClientConnector.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
private void doConnect(EventLoopGroup loupGroup, Class<? extends SocketChannel> serverChannelClass, boolean isEpoll)
		throws InterruptedException {

	final Bootstrap bootstrap = new Bootstrap();

	if (isEpoll) {
		bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
	}

	bootstrap.option(ChannelOption.SO_REUSEADDR, true);
	bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024);
	bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);
	bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, //
			new WriteBufferWaterMark(1024 * 1024, 2048 * 1024));

	bootstrap.group(loupGroup);
	bootstrap.channel(serverChannelClass);
	bootstrap.handler(new BenchmarkChannelInitializer(futureContainer));

	for (int i = 0; i < CONNECT_COUNT; i++) {
		channels[i] = bootstrap.connect(host, port).sync().channel();
		queues[i] = new MpscAtomicArrayQueue<>(4 * 1024);
	}
}
 
Example #19
Source File: DataGeneratorClient.java    From Touchstone with Apache License 2.0 5 votes vote down vote up
private void connect() {
	// configuring the NIO thread groups of the server
	EventLoopGroup group = new NioEventLoopGroup(1);
	// Bootstrap is an assistant class of Netty for setting up client
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.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(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.
					weakCachingConcurrentResolver(this.getClass().getClassLoader())));
			ch.pipeline().addLast(new ObjectEncoder());
			ch.pipeline().addLast(new DataGeneratorClientHandler());
		}
	});
	
	while (true) {
		try {
			Thread.sleep(1000);
			channel = bootstrap.connect(host, port).sync().channel();
			break;
		} catch (Exception e) {
			logger.info("\n\tData generator client startup fail!");
		}
	}
	logger.info("\n\tData generator client startup successful!");
}
 
Example #20
Source File: RpcServer.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
public void bind(ServiceConfig serviceConfig) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(this.rpcServerInitializer)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
        ;

        try {
            ChannelFuture channelFuture = bootstrap.bind(serviceConfig.getHost(),serviceConfig.getPort()).sync();
            RpcURL url=new RpcURL();
            url.setHost(serviceConfig.getHost());
            url.setPort(serviceConfig.getPort());
            url.setRegistryHost(serviceConfig.getRegistryHost());
            url.setRegistryPort(serviceConfig.getRegistryPort());
            RegistryService registryService=new ConsulRegistryService();
            registryService.register(url);
            channelFuture.channel().closeFuture().sync();


        } catch (InterruptedException e) {
            throw new RpcException(e);
        }
    }
    finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #21
Source File: UptimeServer.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(handler);
                        }
                    });

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(PORT).sync();

            // 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();
            bossGroup.shutdownGracefully();
        }
    }
 
Example #22
Source File: MaxNumEventLoopsPerEndpointTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void checkEventLoopAssignedSequentially(
        List<ToIntFunction<Endpoint>> maxNumEventLoopsFunctions, int maxNumEventLoops) {
    final EventLoopGroup group = new DefaultEventLoopGroup(7);
    final List<EventLoop> eventLoops = Streams.stream(group)
                                              .map(EventLoop.class::cast)
                                              .collect(toImmutableList());
    final DefaultEventLoopScheduler s = new DefaultEventLoopScheduler(group, maxNumEventLoops,
                                                                      maxNumEventLoops,
                                                                      maxNumEventLoopsFunctions);

    // endpointA

    EventLoop firstEventLoop = acquireEntry(s, endpointA).get();
    int firstEventLoopIdx = findIndex(eventLoops, firstEventLoop);
    assertThat(firstEventLoopIdx).isIn(0, 1);
    checkNextEventLoopIdx(s, eventLoops, endpointA, firstEventLoopIdx, 0, 2);
    // After one circle, the next event loop is the first one.
    assertThat(firstEventLoop).isSameAs(acquireEntry(s, endpointA).get());

    // endpointB

    firstEventLoop = acquireEntry(s, endpointB).get();
    firstEventLoopIdx = findIndex(eventLoops, firstEventLoop);
    assertThat(firstEventLoopIdx).isIn(2, 3, 4);
    checkNextEventLoopIdx(s, eventLoops, endpointB, firstEventLoopIdx, 2, 3);
    // After one circle, the next event loop is the first one.
    assertThat(firstEventLoop).isSameAs(acquireEntry(s, endpointB).get());

    // endpointC

    firstEventLoop = acquireEntry(s, endpointC).get();
    firstEventLoopIdx = findIndex(eventLoops, firstEventLoop);
    assertThat(firstEventLoopIdx).isIn(0, 1, 2, 5, 6);
    checkNextEventLoopIdx(s, eventLoops, endpointC, firstEventLoopIdx, 5, 5);
    // After one circle, the next event loop is the first one.
    assertThat(firstEventLoop).isSameAs(acquireEntry(s, endpointC).get());
}
 
Example #23
Source File: UdpTestClient.java    From dfactor with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	final EventLoopGroup ioGroup = new NioEventLoopGroup(1);
	//start listen
			Bootstrap boot = new Bootstrap();
			boot.group(ioGroup)
				.option(ChannelOption.SO_BROADCAST, false)
				.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
				.option(ChannelOption.SO_SNDBUF, 1024*10)
				.option(ChannelOption.SO_RCVBUF, 1024*10)
				.channel(NioDatagramChannel.class)
				.handler(new UdpHandlerTestClient());
			try{
				ChannelFuture future = boot.bind(0).sync(); 
				channel = future.channel();
				future.addListener(new GenericFutureListener<Future<? super Void>>() {
					@Override
					public void operationComplete(Future<? super Void> f) throws Exception {
						boolean isDone = f.isDone();
						boolean isSucc = f.isSuccess();
						boolean isCancel = f.isCancelled();
						if(isDone && isSucc){  //listen
							log.I("Init udp succ");
						}else{
							//shutdown io group
							ioGroup.shutdownGracefully();
						}
					}
				});
			}catch(Throwable e){
				e.printStackTrace();
			}
			//start loop
			ExecutorService thPool = Executors.newFixedThreadPool(1);
			thPool.submit(new UdpTestClientLoop());
}
 
Example #24
Source File: AsyncRetryLoop.java    From xio with Apache License 2.0 5 votes vote down vote up
public AsyncRetryLoop(
    int attemptLimit, EventLoopGroup eventLoopGroup, long delay, TimeUnit unit) {
  this.attemptLimit = attemptLimit;
  this.eventLoopGroup = eventLoopGroup;
  this.delay = delay;
  this.unit = unit;
}
 
Example #25
Source File: UdpServerConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelFactory<? extends Channel> connectionFactory(EventLoopGroup elg, boolean isDomainSocket) {
	if (isDomainSocket) {
		throw new UnsupportedOperationException();
	}
	if (isPreferNative()) {
		return () -> loopResources().onChannel(DatagramChannel.class, elg);
	}
	else {
		return () -> new NioDatagramChannel(family());
	}
}
 
Example #26
Source File: NettyServerBuilderTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void assertEventLoopsAndChannelType_allProvided() {
  EventLoopGroup mockEventLoopGroup = mock(EventLoopGroup.class);

  builder.bossEventLoopGroup(mockEventLoopGroup);
  builder.workerEventLoopGroup(mockEventLoopGroup);
  builder.channelType(LocalServerChannel.class);

  builder.assertEventLoopsAndChannelType();
}
 
Example #27
Source File: TimeClient.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String host = "127.0.0.1";//args[0];
    int port = 8080;//Integer.parseInt(args[1]);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new TimeClientHandler());
            }
        });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync(); // (5)

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
 
Example #28
Source File: ServerTest.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Test
public void testTryWithResourcesShouldCloseAllClustersButNotEventLoopIfProvided()
    throws Exception {
  EventLoopGroup eventLoop = new DefaultEventLoopGroup();
  BoundCluster cluster;
  MockClient client;

  try (Server server =
      Server.builder()
          .withAddressResolver(localAddressResolver)
          .withEventLoopGroup(eventLoop, LocalServerChannel.class)
          .build()) {

    cluster = server.register(ClusterSpec.builder().withNodes(5));
    BoundNode node = cluster.node(0);
    SocketAddress address = node.getAddress();
    client = new MockClient(eventLoop);
    client.connect(address);
  }

  // event loop should not have been closed.
  assertThat(eventLoop.isShutdown()).isFalse();
  // timer should have since a custom one was not provided.
  try {
    cluster
        .getServer()
        .timer
        .newTimeout(
            timeout -> {
              // noop
            },
            1,
            TimeUnit.SECONDS);
    fail("Expected IllegalStateException");
  } catch (IllegalStateException ise) {
    // expected
  }
  eventLoop.shutdownGracefully(0, 0, TimeUnit.SECONDS);
}
 
Example #29
Source File: UtilsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultEventLoopGroup_whenEpollIsAvailable() {
  assume().that(Utils.isEpollAvailable()).isTrue();

  EventLoopGroup defaultBossGroup = Utils.DEFAULT_BOSS_EVENT_LOOP_GROUP.create();
  EventLoopGroup defaultWorkerGroup = Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP.create();

  assertThat(defaultBossGroup.getClass().getName())
      .isEqualTo("io.netty.channel.epoll.EpollEventLoopGroup");
  assertThat(defaultWorkerGroup.getClass().getName())
      .isEqualTo("io.netty.channel.epoll.EpollEventLoopGroup");

  defaultBossGroup.shutdownGracefully();
  defaultWorkerGroup.shutdownGracefully();
}
 
Example #30
Source File: ModbusTcpMasterConfig.java    From modbus with Apache License 2.0 5 votes vote down vote up
public ModbusTcpMasterConfig(
    String address,
    int port,
    Duration timeout,
    boolean lazy,
    boolean persistent,
    int maxReconnectDelay,
    String instanceId,
    ExecutorService executor,
    ScheduledExecutorService scheduler,
    EventLoopGroup eventLoop,
    HashedWheelTimer wheelTimer,
    Consumer<Bootstrap> bootstrapConsumer
) {

    this.address = address;
    this.port = port;
    this.timeout = timeout;
    this.lazy = lazy;
    this.persistent = persistent;
    this.maxReconnectDelay = maxReconnectDelay;
    this.instanceId = instanceId;
    this.executor = executor;
    this.scheduler = scheduler;
    this.eventLoop = eventLoop;
    this.wheelTimer = wheelTimer;
    this.bootstrapConsumer = bootstrapConsumer;
}