List of usage examples for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup
public NioEventLoopGroup(ThreadFactory threadFactory)
From source file:cn.david.main.EchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/* w ww .j a v a2s . c o m*/ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new EchoServerHandler()); } }); // 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. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:cn.david.main.PersonServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* w ww . j ava 2 s . c om*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ServerInitializer()); // 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. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:cn.david.socks.SocksServer.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from ww w. j ava 2 s .com ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SocksServerInitializer()); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:cn.npt.net.websocket.WebSocketServer.java
License:Apache License
private void init(int port, boolean ssl, String webSocketPath) throws Exception { final SslContext sslCtx; if (this.ssl) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else {//from w w w . j av a 2 s . c o m sslCtx = null; } bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer(sslCtx, webSocketPath, ssl)); Channel ch = b.bind(this.port).sync().channel(); ch.closeFuture().sync();// } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } System.out.println("start websocket..."); }
From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketBase.java
License:Apache License
private void connect() { try {/*from ww w. ja v a 2s. c o m*/ final URI uri = new URI(url); if (uri == null) { return; } if (uri.getHost().contains("com")) { siteFlag = 1; } group = new NioEventLoopGroup(1); bootstrap = new Bootstrap(); final SslContext sslCtx = SslContext.newClientContext(); final WebSocketClientHandler handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders(), Integer.MAX_VALUE), service, moniter); bootstrap.group(group).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort())); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); future = bootstrap.connect(uri.getHost(), uri.getPort()); future.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { } }); channel = future.sync().channel(); handler.handshakeFuture().sync(); this.setStatus(true); } catch (Exception e) { Log.e(TAG, "WebSocketClient start error " + e.getLocalizedMessage()); group.shutdownGracefully(); this.setStatus(false); } }
From source file:co.rsk.net.discovery.UDPServer.java
License:Open Source License
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();/*w w w .j ava 2 s . c om*/ logger.warn("UDP channel closed. Recreating after 5 sec pause..."); TimeUnit.SECONDS.sleep(5); } group.shutdownGracefully().sync(); }
From source file:code.google.nfs.rpc.netty4.client.Netty4ClientFactory.java
License:Apache License
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception { final Netty4ClientHandler handler = new Netty4ClientHandler(this, key); EventLoopGroup group = new NioEventLoopGroup(1); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))) .option(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout < 1000 ? 1000 : connectTimeout) .handler(new ChannelInitializer<SocketChannel>() { @Override// w w w . j av a2s . co m public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder()); ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder()); ch.pipeline().addLast("handler", handler); } }); ChannelFuture future = b.connect(targetIP, targetPort); future.awaitUninterruptibly(connectTimeout); if (!future.isDone()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!"); } if (future.isCancelled()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); } if (!future.isSuccess()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); } Netty4Client client = new Netty4Client(future, key, connectTimeout); handler.setClient(client); return client; }
From source file:com.addthis.hydra.query.web.QueryServer.java
License:Apache License
public void run() throws Exception { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); executorGroup = new DefaultEventExecutorGroup(AggregateConfig.FRAME_READER_THREADS, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("frame-reader-%d").build()); for (EventExecutor executor : executorGroup) { executor.execute(new NextQueryTask(queryQueue, executor)); }/*from w w w . j a v a 2 s.c o m*/ ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.childOption(ChannelOption.MESSAGE_SIZE_ESTIMATOR, new DefaultMessageSizeEstimator(200)); b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 100000000); b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 50000000); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(queryServerInitializer); b.bind(webPort).sync(); }
From source file:com.addthis.meshy.MeshyServer.java
License:Apache License
public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group) throws IOException { super();/* ww w.jav a 2 s . c o m*/ this.group = group; this.rootDir = rootDir; this.filesystems = loadFileSystems(rootDir); this.serverPeers = new AtomicInteger(0); bossGroup = new NioEventLoopGroup(1); ServerBootstrap bootstrap = new ServerBootstrap() .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK) .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK) .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(final NioSocketChannel ch) throws Exception { ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch)); } }); /* bind to one or more interfaces, if supplied, otherwise all */ if ((netif == null) || (netif.length == 0)) { ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port)) .syncUninterruptibly().channel(); serverLocal = serverChannel.localAddress(); } else { InetSocketAddress primaryServerLocal = null; for (String net : netif) { NetworkInterface nicif = NetworkInterface.getByName(net); if (nicif == null) { log.warn("missing speficied NIC: {}", net); continue; } for (InterfaceAddress addr : nicif.getInterfaceAddresses()) { InetAddress inAddr = addr.getAddress(); if (inAddr.getAddress().length != 4) { log.trace("skip non-ipV4 address: {}", inAddr); continue; } ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel(); if (primaryServerLocal != null) { log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal); } primaryServerLocal = serverChannel.localAddress(); } } if (primaryServerLocal == null) { throw new IllegalArgumentException("no valid interface / port specified"); } serverLocal = primaryServerLocal; } this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress()); this.serverPort = serverLocal.getPort(); if (serverNetIf != null) { serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName(); } else { serverUuid = super.getUUID() + "-" + serverPort; } log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir); closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> { bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> { if (!workerFuture.isSuccess()) { closeFuture.tryFailure(workerFuture.cause()); } else if (!bossFuture.isSuccess()) { closeFuture.tryFailure(bossFuture.cause()); } else { closeFuture.trySuccess(null); } }); }); addMessageFileSystemPaths(); group.join(this); if (autoMesh) { startAutoMesh(serverPort, autoMeshTimeout); } }
From source file:com.adobe.acs.livereload.impl.LiveReloadServerImpl.java
License:Apache License
@Activate protected void activate(ComponentContext ctx) throws Exception { Dictionary<?, ?> props = ctx.getProperties(); this.port = PropertiesUtil.toInteger(props.get(PROP_PORT), DEFAULT_PORT); this.pathPrefixes = PropertiesUtil.toStringArray(props.get(PROP_PREFIXES), DEFAULT_PREFIXES); this.broadcastGroup = new NioEventLoopGroup(1); this.group = new DefaultChannelGroup("live-reload", broadcastGroup.next()); this.infos = new ConcurrentHashMap<Channel, ChannelInfo>(); this.matcher = new ContentPageMatcher(); startServer();//from w w w .ja va 2s .co m running = true; if (PropertiesUtil.toBoolean(props.get(PROP_JS_FILTER_ENABLED), DEFAULT_JS_FILTER_ENABLED)) { Dictionary<Object, Object> filterProps = new Hashtable<Object, Object>(); filterProps.put("sling.filter.scope", "request"); filterProps.put("filter.order", FILTER_ORDER); filterReference = ctx.getBundleContext().registerService(Filter.class.getName(), new JavaScriptInjectionFilter(port, pathPrefixes), filterProps); } }