Java Code Examples for io.netty.channel.nio.NioEventLoopGroup

The following are top voted examples for showing how to use io.netty.channel.nio.NioEventLoopGroup. 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: webapp-tyust   File: NettyServer.java   Source Code and License 9 votes vote down vote up
private NettyServer(){
	pGroup = new NioEventLoopGroup();
	cGroup = new NioEventLoopGroup();
	serverBootstrap = new ServerBootstrap();
	serverBootstrap.group(pGroup, cGroup)
	 .channel(NioServerSocketChannel.class)
	 .option(ChannelOption.SO_BACKLOG, 1024)
	 //设置日志
	 .handler(new LoggingHandler(LogLevel.INFO))
	 .childHandler(new ChannelInitializer<SocketChannel>() {
		protected void initChannel(SocketChannel sc) throws Exception {
			sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
			sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
			sc.pipeline().addLast(new ReadTimeoutHandler(60));
			sc.pipeline().addLast(new NettyServerHandler());
		}
	});		
}
 
Example 2
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 3
Project: jeesupport   File: NettyServer.java   Source Code and License 6 votes vote down vote up
public void start(){
	logger.debug( "--Socket Server will start------------" ) ;
	boss = new NioEventLoopGroup() ;
	work = new NioEventLoopGroup() ;
	int port = CommonConfig.getInteger( SOCKET_PORT1 );
	try {
		
		logger.info( "Netty Server[" + port + "] started..." ) ;
		ServerBootstrap b = new ServerBootstrap() ;

		b.group( boss , work ) ;
		b.channel( NioServerSocketChannel.class ) ;
		b.childHandler( nettyInitializer ) ;
		b.bind( port ).sync().channel().closeFuture().sync() ;
	} catch ( Exception e ) {
		String err_string = e.toString();
		if( err_string.indexOf( "childHandler" ) != -1 ){
			logger.error( "Netty Server[" + port + "] NettyInitializer can't find." ) ;
		}else{
			logger.error( "Netty Server[" + port + "] onload err:" + e.toString() , e  ) ;
		}
	} finally {
		logger.error( "Netty Server[" + port + "] will be unload..."  ) ;
		unload();
	}
}
 
Example 4
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 5
Project: redant   File: SlaveServer.java   Source Code and License 6 votes vote down vote up
public void start(SlaveNode slaveNode) {
    if(slaveNode==null){
        throw new IllegalArgumentException("slaveNode is null");
    }
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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 SlaveServerInitializer());

        ChannelFuture future = b.bind(slaveNode.getPort()).sync();
        LOGGER.info("SlaveServer Startup at port:{}",slaveNode.getPort());

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 6
Project: redant   File: MasterServer.java   Source Code and License 6 votes vote down vote up
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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 MasterServerInitializer());

        ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
        LOGGER.info("MasterServer Startup at port:{}",CommonConstants.SERVER_PORT);

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 7
Project: redant   File: NettyServer.java   Source Code and License 6 votes vote down vote up
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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());

        ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
        logger.info("NettyServer Startup at port:{}",CommonConstants.SERVER_PORT);

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 8
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 9
Project: mapsforge-web   File: HttpServer.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	EventLoopGroup bossGroup = new NioEventLoopGroup();
       EventLoopGroup workerGroup = new NioEventLoopGroup();
       
       try{
           ServerBootstrap serverBootstrap = new ServerBootstrap();
           serverBootstrap.group(bossGroup,workerGroup)
           		.channel(NioServerSocketChannel.class)
           		.childHandler(new HttpServer());
           ChannelFuture channelFuture = serverBootstrap
           		.bind(new InetSocketAddress("0.0.0.0", PORT))
           		.sync();
           channelFuture.channel().closeFuture().sync();
       } finally {
           bossGroup.shutdownGracefully();
           workerGroup.shutdownGracefully();
       }
}
 
Example 10
Project: monica   File: SocketClient.java   Source Code and License 6 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 11
Project: ss-java   File: ShadowsocksClient.java   Source Code and License 6 votes vote down vote up
public Future startAsync() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new SocksServerInitializer())
             .childAttr(OPTION_ATTRIBUTE_KEY, option);

    return bootstrap.bind(option.getLocalHost(), option.getLocalPort()).addListener(
            new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (infoEnable) {
                        if (future.isSuccess()) {
                            logger.info("Listening on local port {}", option.getLocalPort());
                        } else {
                            logger.info("Shadowsocks client startup failed", future.cause());
                        }
                    }
                }
            });
}
 
Example 12
Project: TakinRPC   File: RemotingNettyClient.java   Source Code and License 6 votes vote down vote up
private RemotingNettyClient(final NettyClientConfig nettyClientConfig) {
    super(nettyClientConfig.getOnewaySemaphoreValue(), nettyClientConfig.getAsyncSemaphoreValue());
    int publicThreadNums = nettyClientConfig.getCallbackExecutorThreads();
    if (publicThreadNums <= 0) {
        publicThreadNums = 4;
    }
    this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyClientPublicExecutor_" + this.threadIndex.incrementAndGet());
        }
    });

    group = new NioEventLoopGroup(nettyClientConfig.getWorkerThreads(), new CustomThreadFactory("client"));

    start();
}
 
Example 13
Project: Jenisys3   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 14
Project: guereza   File: NettyServer.java   Source Code and License 6 votes vote down vote up
/**
 * Start the server
 *
 * @param port The port on which the server listen to
 */
public void run(final int port) {
    final EventLoopGroup bossGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        final ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer())
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true);

        final ChannelFuture f = bootstrap.bind(port).sync();
        LOGGER.info("NettyServer: running on port {}", port);

        f.channel().closeFuture().sync();
    } catch (final InterruptedException e) {
        LOGGER.error("NettyServer: an error occurred while running: {}", e.getMessage());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 15
Project: push   File: Client.java   Source Code and License 6 votes vote down vote up
public void run() {
	workerGroup = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(workerGroup);
		b.channel(NioSocketChannel.class);
		// b.option(ChannelOption.SO_KEEPALIVE, true);
		b.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
				pipeline.addLast("decoder", new MsgPackDecode());
				pipeline.addLast("encoder", new MsgPackEncode());
				pipeline.addLast(new ClientHandler());
			}
		});
		channel = b.connect(clientProperties.getServerHost(), clientProperties.getServerPort()).sync().channel();
		status = Status.START;
		channel.closeFuture().sync();
	} catch (Exception e) {
		e.printStackTrace();
	}
	status = Status.STOP;
}
 
Example 16
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 17
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 18
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 19
Project: mini-dubbo   File: NettyServer.java   Source Code and License 6 votes vote down vote up
public void doOpen() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast((SimpleChannelInboundHandler)handler);
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
        ChannelFuture future = serverBootstrap.bind(address,port).sync();
        //future.channel().closeFuture().sync();
    }finally{
        //workerGroup.shutdownGracefully();
        //bossGroup.shutdownGracefully();
    }
}
 
Example 20
Project: Mods   File: TF2UdpClient.java   Source Code and License 6 votes vote down vote up
public TF2UdpClient(InetSocketAddress address) throws Exception {
	group = new NioEventLoopGroup();
	this.address = address;
	EntityPlayerSP player = Minecraft.getMinecraft().player;
	Bootstrap boot = new Bootstrap();
	boot.group(group).channel(NioDatagramChannel.class).handler(new UdpChannelHandlerClient());
	
	channel = boot.bind(0).sync().channel();
	
	channel.connect(address);
	
	/*PacketBuffer buffer = new PacketBuffer(Unpooled.buffer());
	buffer.writeShort(playerId);
	buffer.writeShort(0);
	buffer.writeByte(0);
	buffer.writeLong(System.currentTimeMillis());
	
	channel.writeAndFlush(new DatagramPacket(buffer, address));*/
}
 
Example 21
Project: talchain   File: UdpTest.java   Source Code and License 6 votes vote down vote up
public Channel create(String bindAddr, int port) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);

    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new PacketDecoder());
                SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
                nodeManager.setMessageSender(messageHandler);
                ch.pipeline().addLast(messageHandler);
            }
        });

    return b.bind(bindAddr, port).sync().channel();
}
 
Example 22
Project: sds   File: NettyServerServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public synchronized void start() {
    bossGroup = new NioEventLoopGroup(); // (1)
    workerGroup = new NioEventLoopGroup();
    try {
        b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SocketServerChannelInitializer(heartTime,socketService,applicationContext));
        // Bind and start to accept incoming connections.
        b.bind(port);

        logger.info("socket: "+port+" starting....");
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 23
Project: neoscada   File: Receiver.java   Source Code and License 6 votes vote down vote up
public Receiver ( final ReceiverHandlerFactory factory, final SocketAddress addr )
{
    this.factory = factory;

    this.bossGroup = new NioEventLoopGroup ();
    this.workerGroup = new NioEventLoopGroup ();
    this.bootstrap = new ServerBootstrap ();
    this.bootstrap.group ( this.bossGroup, this.workerGroup );
    this.bootstrap.channel ( NioServerSocketChannel.class );
    this.bootstrap.option ( ChannelOption.SO_BACKLOG, 5 );
    this.bootstrap.option ( ChannelOption.SO_REUSEADDR, true );
    this.bootstrap.childHandler ( new ChannelInitializer<SocketChannel> () {

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

    this.channel = this.bootstrap.bind ( addr ).channel ();

    logger.info ( "Receiver running ..." );
}
 
Example 24
Project: chromium-net-for-android   File: Http2TestServer.java   Source Code and License 6 votes vote down vote up
public void run() {
    try {
        // Configure the server.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new Http2ServerInitializer(mSslCtx));

            sServerChannel = b.bind(PORT).sync().channel();
            Log.i(TAG, "Netty HTTP/2 server started on " + getServerUrl());
            sBlock.open();
            sServerChannel.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
        Log.i(TAG, "Stopped Http2TestServerRunnable!");
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}
 
Example 25
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 26
Project: iothub   File: MqttTransportService.java   Source Code and License 6 votes vote down vote up
@PostConstruct
public void init() throws Exception {
  log.info("Setting resource leak detector level to {}", leakDetectorLevel);
  ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

  log.info("Starting MQTT transport...");
  log.info("Lookup MQTT transport adaptor {}", adaptorName);
  // this.adaptor = (MqttTransportAdaptor) appContext.getBean(adaptorName);

  log.info("Starting MQTT transport server");
  bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
  workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.TCP_NODELAY, true)
      .childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
      .childHandler(new MqttTransportServerInitializer(msgProducer, deviceService, authService, assetService,
          assetAuthService, relationService, sslHandlerProvider));

  serverChannel = b.bind(host, port).sync().channel();
  log.info("Mqtt transport started: {}:{}!", host, port);
}
 
Example 27
Project: im   File: EchoServer.java   Source Code and License 6 votes vote down vote up
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example 28
Project: netty-socks   File: ServerMain.java   Source Code and License 6 votes vote down vote up
public void start() throws InterruptedException {
    EventLoopGroup acceptors = new NioEventLoopGroup(socksProperties.getAcceptors());
    EventLoopGroup workers = new NioEventLoopGroup();
    EventLoopGroup forwarders = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(acceptors, workers)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, socksProperties.getBacklog())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, socksProperties.getConnectTimeoutMillis())
                .childHandler(new Socks5WorkerChannelInitializer(socksProperties, forwarders));

        Address address = socksProperties.getListen();
        ChannelFuture future = bootstrap.bind(address.getHost(), address.getPort()).sync();
        future.channel().closeFuture().sync();
    } finally {
        forwarders.shutdownGracefully();
        workers.shutdownGracefully();
        acceptors.shutdownGracefully();
    }
}
 
Example 29
Project: http-proxy-netty   File: HttpProxyServer.java   Source Code and License 6 votes vote down vote up
@PostConstruct
public void start() {
    new Thread(() -> {
        logger.info("HttpProxyServer started on port: {}", port);
        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.DEBUG))
                    .childHandler(channelInitializer)
                    .bind(port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("shit happens", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }).start();
}
 
Example 30
Project: push-server   File: NettyServerBootstrap.java   Source Code and License 6 votes vote down vote up
private void bind() throws InterruptedException {
    EventLoopGroup boss = new NioEventLoopGroup(1);
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new NettyServerInitializer());

    ChannelFuture f = bootstrap.bind(port).sync();
    if (f.isSuccess()) {
        logger.info("server start---------------");
    }
}
 
Example 31
Project: rskj   File: UDPServer.java   Source Code and License 6 votes vote down vote up
public void startUDPServer() throws InterruptedException {
    logger.info("Discovery UDPListener started");
    EventLoopGroup group = new NioEventLoopGroup(1);

    while (!shutdown) {
        Bootstrap bootstrap = this.createBootstrap(group);

        channel = bootstrap.bind(address, port).sync().channel();
        channel.closeFuture().sync();

        logger.warn("UDP channel closed. Recreating after 5 sec pause...");
        TimeUnit.SECONDS.sleep(5);
    }

    group.shutdownGracefully().sync();
}
 
Example 32
Project: rskj   File: JsonRpcNettyServer.java   Source Code and License 6 votes vote down vote up
public JsonRpcNettyServer(InetAddress host,
                          int port,
                          int socketLinger,
                          boolean reuseAddress,
                          CorsConfiguration corsConfiguration,
                          JsonRpcWeb3FilterHandler jsonRpcWeb3FilterHandler,
                          JsonRpcWeb3ServerHandler jsonRpcWeb3ServerHandler) {
    this.host = host;
    this.port = port;
    this.socketLinger = socketLinger;
    this.reuseAddress = reuseAddress;
    this.corsConfiguration = corsConfiguration;
    this.jsonRpcWeb3FilterHandler = jsonRpcWeb3FilterHandler;
    this.jsonRpcWeb3ServerHandler = jsonRpcWeb3ServerHandler;
    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
}
 
Example 33
Project: teslog   File: HttpHelloWorldServer.java   Source Code and License 5 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;
    }

    // Configure the server.
    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 HttpHelloWorldServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " +
                (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 34
Project: DNCF   File: NettyConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(name = "workerGroup")
public EventLoopGroup getWorkerGroup() {
    if (isLinux) {
        return new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNCSWorkerThread", Thread.NORM_PRIORITY));
    } else {
        return new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNCSWorkerThread", Thread.NORM_PRIORITY));
    }
}
 
Example 35
Project: GitHub   File: NettyHttpClient.java   Source Code and License 5 votes vote down vote up
@Override public void prepare(final Benchmark benchmark) {
  this.concurrencyLevel = benchmark.concurrencyLevel;
  this.targetBacklog = benchmark.targetBacklog;

  ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
    @Override public void initChannel(SocketChannel channel) throws Exception {
      ChannelPipeline pipeline = channel.pipeline();

      if (benchmark.tls) {
        SslClient sslClient = SslClient.localhost();
        SSLEngine engine = sslClient.sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        pipeline.addLast("ssl", new SslHandler(engine));
      }

      pipeline.addLast("codec", new HttpClientCodec());
      pipeline.addLast("inflater", new HttpContentDecompressor());
      pipeline.addLast("handler", new HttpChannel(channel));
    }
  };

  bootstrap = new Bootstrap();
  bootstrap.group(new NioEventLoopGroup(concurrencyLevel))
      .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
      .channel(NioSocketChannel.class)
      .handler(channelInitializer);
}
 
Example 36
Project: hadoop   File: WebImageViewer.java   Source Code and License 5 votes vote down vote up
public WebImageViewer(InetSocketAddress address) {
  this.address = address;
  this.bossGroup = new NioEventLoopGroup();
  this.workerGroup = new NioEventLoopGroup();
  this.allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
  this.bootstrap = new ServerBootstrap()
    .group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class);
}
 
Example 37
Project: push-network-proxies   File: NotificationRegisterEndpoint.java   Source Code and License 5 votes vote down vote up
protected void startNotificationRegisterEndpoint(final String host, final int port) {

        Runnable notificationRegisterEndpointRunnable = new Runnable() {

            @Override
            public void run() {
                bossGroup = new NioEventLoopGroup(1);
                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 NotificationRegisterServerInitializer());

                    Channel ch = b.bind(host, port).sync().channel();

                    logger.info(String.format("Notification register endpoint started at %s:%s", host, port));

                    ch.closeFuture().sync();
                } catch (InterruptedException ex) {
                    logger.info("Notification register endpoint was interrupted.");
                } finally {
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                }

            }
        };

        notificationEndpointThread = new Thread(notificationRegisterEndpointRunnable);
        notificationEndpointThread.start();
    }
 
Example 38
Project: DNCF   File: NettyConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(name = "workerGroup")
public EventLoopGroup getWorkerGroup() {
    if (isLinux) {
        return new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNWorkerThread", Thread.NORM_PRIORITY));
    } else {
        return new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNWorkerThread", Thread.NORM_PRIORITY));
    }
}
 
Example 39
Project: BedrockProxy   File: RakNetServer.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a <code>RakNetServer</code> with the specified port, maximum
 * amount connections, maximum transfer unit, and <code>Identifier</code>.
 *
 * @param port                the server port.
 * @param maxConnections      the maximum amount of connections.
 * @param maximumTransferUnit the maximum transfer unit.
 * @param identifier          the <code>Identifier</code>.
 */
public RakNetServer(int port, int maxConnections, int maximumTransferUnit, Identifier identifier) {
    // Set server data
    this.guid = new Random().nextLong();
    this.timestamp = System.currentTimeMillis();
    this.port = port;
    this.maxConnections = maxConnections;
    this.maximumTransferUnit = maximumTransferUnit;
    this.broadcastingEnabled = true;
    this.identifier = identifier;

    // Initiate bootstrap data
    this.bootstrap = new Bootstrap();
    this.group = new NioEventLoopGroup();
    this.handler = new RakNetServerHandler(this);

    // Set listener
    this.listener = this;

    // Create session map
    this.sessions = new ConcurrentHashMap<InetSocketAddress, RakNetClientSession>();

    // Check maximum transfer unit
    if (this.maximumTransferUnit < RakNet.MINIMUM_TRANSFER_UNIT) {
        throw new IllegalArgumentException(
                "Maximum transfer unit can be no smaller than " + RakNet.MINIMUM_TRANSFER_UNIT);
    }
}
 
Example 40
Project: Quavo   File: NetworkExecutor.java   Source Code and License 5 votes vote down vote up
/**
 * Starts the network for a {@link Server}.
 * 
 * @param server The {@link Server} to use for building the network.
 * @return <True> If the network started successfully.
 */
public static void start() {
	EventLoopGroup boss = new NioEventLoopGroup();
	EventLoopGroup worker = new NioEventLoopGroup();
	ServerBootstrap bootstrap = new ServerBootstrap();

	bootstrap.group(boss, worker);
	bootstrap.channel(NioServerSocketChannel.class);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();

			pipeline.addLast("decoder", new ConnectionDecoder());
			pipeline.addLast("encoder", new ConnectionEncoder());
			pipeline.addLast("adapter", new NetworkMessageHandler());
		}

	});
	bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

	try {
		bootstrap.bind(Constants.HOST_NAME, Constants.HOST_PORT).sync();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}

	System.out.println("Server successfully bootstrapped on port " + Constants.HOST_PORT + " and address " + Constants.HOST_NAME + ".");
}