List of usage examples for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup
public NioEventLoopGroup(ThreadFactory threadFactory)
From source file:com.ancun.netty.common.NettyBootstrapFactory.java
License:Apache License
/** * NIOnetty?// w w w . java 2 s . c om * * @param ioThreadCount * @return NIOnetty? */ private ServerBootstrap newNioServerBootstrap(int ioThreadCount) { bossGroup = new NioEventLoopGroup(1); if (ioThreadCount > 0) { workerGroup = new NioEventLoopGroup(ioThreadCount); } else { workerGroup = new NioEventLoopGroup(); } return new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class); }
From source file:com.andrewkroh.cicso.rtp.NettyRtpSession.java
License:Apache License
public NettyRtpSession(final InetSocketAddress bindAddress, final NetworkInterface multicastInterface, final InetAddress multicastGroup) { Preconditions.checkNotNull(bindAddress, "Must specify a bind address."); if (multicastGroup != null) { Preconditions.checkNotNull(multicastInterface, "When specifying the multicast group you must also " + "specify the multicast interface."); // Javadoc for Java 7 MulticastChannel states: The channel's // socket should be bound to the wildcard address. If the socket // is bound to a specific address, rather than the wildcard address // then it is implementation specific if multicast datagrams // are received by the socket. Preconditions.checkArgument(bindAddress.getAddress().isAnyLocalAddress(), "Must bind to wildcard address when using multicast."); }/*from ww w . ja v a 2s . c o m*/ EventLoopGroup workerGroup = new NioEventLoopGroup(NUM_THREADS); bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_REUSEADDR, true) .localAddress(bindAddress).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new RtpPacketHandler(NettyRtpSession.this)); } }); if (multicastGroup != null) { bootstrap.option(ChannelOption.IP_MULTICAST_TTL, MULTICAST_TTL); // All multicast traffic generated from this channel will be // output from this interface. If not specified it will use the OS // default which may be unpredicatable: bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface); } channel = (DatagramChannel) bootstrap.bind().syncUninterruptibly().channel(); LOGGER.info("Session bound to: {}", channel.localAddress()); if (multicastGroup != null) { channel.joinGroup(multicastGroup, multicastInterface, null).syncUninterruptibly(); LOGGER.info("Session bound to multicast group {} on interface {}.", multicastGroup.getHostAddress(), multicastInterface.getDisplayName()); } else { LOGGER.info("Session will not be a multicast listener because " + "no multicast group was specified."); } }
From source file:com.artigile.homestats.HomeStatsServer.java
License:Apache License
public static void main(String[] args) throws Exception { ArgsParser argsParser = new ArgsParser(args); if (argsParser.isDisplayHelp()) { ArgsParser.printHelp();/*www .j ava2 s . c om*/ return; } EventLoopGroup bossGroup = null; EventLoopGroup workerGroup = null; try { SensorMode appMode = SensorMode .valueOf(argsParser.getString(ArgsParser.APP_MODE_OPTION, "dev").toUpperCase()); SensorsDataProvider sensorsDataProvider = SensorFactory.buildSensorDataProvider(appMode); if (sensorsDataProvider == null) { LOGGER.error("No sensor device available, quitting."); return; } final boolean printAndExit = argsParser.argumentPassed(ArgsParser.PRINT_AND_EXIT); if (printAndExit) { sensorsDataProvider.printAll(); return; } final String dbHost = argsParser.getString(DB_HOST_OPTION, "localhost"); final String user = argsParser.getString(DB_USER_OPTION); final String pwd = argsParser.getString(DB_PWD_OPTION); final int port = Integer.valueOf(argsParser.getString(APP_PORT_OPTION, PORT + "")); LOGGER.info("Connecting to {}, user {}, pwd: {}", dbHost, user, pwd); final DbDao dbDao = new DbDao(dbHost, user, pwd); new DataService(sensorsDataProvider, dbDao, 1000 * 60 * 5).start(); // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } // Configure the server. bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)) .childHandler(new HomeStatsServerInitializer(sslCtx, dbDao, sensorsDataProvider)); 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 { if (bossGroup != null) { bossGroup.shutdownGracefully(); } if (workerGroup != null) { workerGroup.shutdownGracefully(); } } }
From source file:com.avanza.astrix.netty.server.NettyRemotingServer.java
License:Apache License
public void start() { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, false).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from ww w . jav a 2s . c om*/ public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new NettyRemotingServerHandler(serviceActivator)); } }); // Bind and start to accept incoming connections. Binds to all interfaces // TODO: Allow specifying a bind port range. Attempt to bind to each port in range and use first successfully bound port ChannelFuture channel = b.bind(port); try { if (channel.await(2, TimeUnit.SECONDS)) { if (channel.isSuccess()) { port = InetSocketAddress.class.cast(channel.channel().localAddress()).getPort(); log.info("NettyRemotingServer started listening on port={}", port); return; } } } catch (InterruptedException e) { } throw new IllegalStateException("Failed to start netty remoting server. Can't bind to port: " + port); }
From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServer.java
License:Apache License
public RpcServer(Class<? extends ServerChannel> serverChannelClass, RpcServerOptions serverOptions, RpcServiceRegistry rpcServiceRegistry) { if (rpcServiceRegistry == null) { throw new RuntimeException("protperty 'rpcServiceRegistry ' is null."); }//from w w w. ja va 2 s. c o m if (serverOptions == null) { serverOptions = new RpcServerOptions(); } this.bossGroup = new NioEventLoopGroup(serverOptions.getAcceptorThreads()); this.workerGroup = new NioEventLoopGroup(serverOptions.getWorkThreads()); this.group(this.bossGroup, this.workerGroup); this.channel(serverChannelClass); this.option(ChannelOption.SO_BACKLOG, serverOptions.getBacklog()); this.childOption(ChannelOption.SO_KEEPALIVE, serverOptions.isKeepAlive()); this.childOption(ChannelOption.SO_REUSEADDR, true); this.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); this.childOption(ChannelOption.TCP_NODELAY, serverOptions.isTcpNoDelay()); this.childOption(ChannelOption.SO_LINGER, serverOptions.getSoLinger()); this.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, serverOptions.getConnectTimeout()); this.childOption(ChannelOption.SO_RCVBUF, serverOptions.getReceiveBufferSize()); this.childOption(ChannelOption.SO_SNDBUF, serverOptions.getSendBufferSize()); this.rpcServiceRegistry = rpcServiceRegistry; // do register meta service rpcServiceRegistry.doRegisterMetaService(); this.rpcServerOptions = serverOptions; this.rpcServerPipelineInitializer = new RpcServerPipelineInitializer(rpcServiceRegistry, rpcServerOptions); this.childHandler(rpcServerPipelineInitializer); }
From source file:com.baidu.rigel.biplatform.ma.file.client.service.impl.FileServerClient.java
License:Open Source License
/** * ?//from ww w . j a v a 2 s . c o m * * @param server * ?? * @param port * ?? * @param request * * @return */ public Response doRequest(String server, int port, final Request request) { EventLoopGroup work = new NioEventLoopGroup(1); String message = null; try { final Response rs = new Response(ResponseStatus.FAIL, "failed", null); ChannelHandlerAdapter requestHandler = new ChannelHandlerAdapter() { /** * {@inheritDoc} */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("successfully connect to file server"); ctx.write(request); ctx.flush(); } /** * {@inheritDoc} */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.info("successfuly recieve message from file server {}", msg); Response tmpRs = (Response) msg; rs.setDatas(tmpRs.getDatas()); rs.setMessage(tmpRs.getMessage()); rs.setStatus(tmpRs.getStatus()); ctx.close(); } /** * {@inheritDoc} */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } /** * {@inheritDoc} */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error(cause.getMessage()); rs.setMessage(cause.getMessage()); rs.setStatus(ResponseStatus.FAIL); ctx.close(); } }; Bootstrap strap = new Bootstrap(); strap.group(work).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel chl) throws Exception { // ?? chl.pipeline().addLast(new ObjectDecoder( ClassResolvers.cacheDisabled(requestHandler.getClass().getClassLoader()))); chl.pipeline().addLast(new ObjectEncoder()); chl.pipeline().addLast(requestHandler); } }); long begin = System.currentTimeMillis(); logger.debug("Begin invoke do file operation request ... ..."); ChannelFuture future = strap.connect(server, port); future.channel().closeFuture().sync(); logger.debug( "Success execute request option cost time: " + (System.currentTimeMillis() - begin) + "ms"); return rs; } catch (InterruptedException e) { logger.error(e.getMessage(), e); message = e.getMessage(); } finally { work.shutdownGracefully(); } Response rs = new Response(ResponseStatus.FAIL, message, null); return rs; }
From source file:com.baidu.rigel.biplatform.ma.file.serv.FileServer.java
License:Open Source License
private static void startServer(String location, int port) { fileLocation = new FileLocation(location); service = new LocalFileOperationServiceImpl(fileLocation); EventLoopGroup bossGroup = new NioEventLoopGroup(10); EventLoopGroup workGroup = new NioEventLoopGroup(50); try {/*from w w w. j av a 2 s.co m*/ ServerBootstrap strap = new ServerBootstrap(); strap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { // ?? channel.pipeline().addLast(new ObjectDecoder(ClassResolvers .weakCachingConcurrentResolver(FileServer.class.getClassLoader()))); channel.pipeline().addLast(new ObjectEncoder()); // channel.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler()); channel.pipeline().addLast(new FileServer()); } }); ChannelFuture future = strap.bind(port).sync(); LOGGER.info("start file server successfully"); LOGGER.info("port : " + port); LOGGER.info("location : " + location); future.channel().closeFuture().sync(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); LOGGER.error("can not start file server with [port : {}] and fileLocation {{}}", port, location); printUsage(); System.exit(-1); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } }
From source file:com.barchart.http.handlers.TestCancellableRequestHandler.java
License:BSD License
@Before public void setUp() throws Exception { server = new HttpServer(); basic = new TestRequestHandler("basic", false, 0, 0, false); async = new TestRequestHandler("async", true, 0, 0, false); asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false); clientDisconnect = new TestRequestHandler("client-disconnect", true, 500, 500, false); error = new TestRequestHandler("error", false, 0, 0, true); final HttpServerConfig config = new HttpServerConfig().requestHandler("/basic", basic) .address(new InetSocketAddress("localhost", 8888)).parentGroup(new NioEventLoopGroup(1)) .childGroup(new NioEventLoopGroup(1)).requestHandler("/async", async) .requestHandler("/async-delayed", asyncDelayed) .requestHandler("/client-disconnect", clientDisconnect).requestHandler("/error", error) .maxConnections(1);//from ww w .ja v a2s. co m server.configure(config).listen().sync(); client = new DefaultHttpClient(new PoolingClientConnectionManager()); }
From source file:com.barchart.http.server.TestHttpServer.java
License:BSD License
@Before public void setUp() throws Exception { server = new HttpServer(); basic = new TestRequestHandler("basic", false, 0, 0, false, false); async = new TestRequestHandler("async", true, 0, 0, false, false); asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false); clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false); error = new TestRequestHandler("error", false, 0, 0, true, false); channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true); infoHandler = new TestRequestHandler("info", false, 0, 0, false, false); serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false); final ServerSocket s = new ServerSocket(0); port = s.getLocalPort();//from www . j a v a 2 s . com s.close(); final HttpServerConfig config = new HttpServerConfig().requestHandler("/basic", basic) .address(new InetSocketAddress("localhost", port)).parentGroup(new NioEventLoopGroup(1)) .childGroup(new NioEventLoopGroup(1)).requestHandler("/async", async) .requestHandler("/async-delayed", asyncDelayed) .requestHandler("/client-disconnect", clientDisconnect) .requestHandler("/channel-error", channelError).requestHandler("/error", error) .requestHandler("/service/info", infoHandler).requestHandler("/service", serviceHandler) .maxConnections(1); server.configure(config).listen().sync(); client = new DefaultHttpClient(new PoolingClientConnectionManager()); }
From source file:com.barchart.netty.server.http.TestHttpServer.java
License:BSD License
@Before public void setUp() throws Exception { basic = new TestRequestHandler("basic", false, 0, 0, false, false); async = new TestRequestHandler("async", true, 0, 0, false, false); asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false); clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false); error = new TestRequestHandler("error", false, 0, 0, true, false); channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true); infoHandler = new TestRequestHandler("info", false, 0, 0, false, false); serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false); chunkedHandler = new ChunkedRequestHandler("chunked"); final ServerSocket s = new ServerSocket(0); port = s.getLocalPort();/*from w ww.j a va2 s . c om*/ s.close(); Thread.sleep(100); server = Servers.createHttpServer().requestHandler("/basic", basic).group(new NioEventLoopGroup(1)) .requestHandler("/async", async).requestHandler("/async-delayed", asyncDelayed) .requestHandler("/client-disconnect", clientDisconnect) .requestHandler("/channel-error", channelError).requestHandler("/error", error) .requestHandler("/service/info", infoHandler).requestHandler("/service", serviceHandler) .requestHandler("/chunked", chunkedHandler).maxConnections(1); server.listen(port, "localhost").sync(); connMgr = new PoolingClientConnectionManager(); client = new DefaultHttpClient(connMgr); }