List of usage examples for io.netty.channel ChannelOption ALLOCATOR
ChannelOption ALLOCATOR
To view the source code for io.netty.channel ChannelOption ALLOCATOR.
Click Source Link
From source file:de.saxsys.synchronizefx.netty.base.client.NettyBasicClient.java
License:Open Source License
@Override public void connect() throws SynchronizeFXException { this.eventLoopGroup = new NioEventLoopGroup(); BasicChannelInitializerClient channelInitializer = createChannelInitializer(); channelInitializer.setTopologyCallback(callback); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT).handler(channelInitializer); LOG.info("Connecting to server"); try {/* w ww.j av a 2 s.c o m*/ ChannelFuture future = bootstrap.connect(address); if (!future.await(TIMEOUT)) { disconnect(); throw new SynchronizeFXException("Timeout while trying to connect to the server."); } if (!future.isSuccess()) { disconnect(); throw new SynchronizeFXException("Connection to the server failed.", future.cause()); } this.channel = future.channel(); channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(final Future<? super Void> future) throws Exception { // stop the event loop eventLoopGroup.shutdownGracefully(); } }); } catch (InterruptedException e) { disconnect(); throw new SynchronizeFXException(e); } }
From source file:divconq.api.HyperSession.java
License:Open Source License
public Channel allocateHttpChannel(final ChannelHandler handler, OperationResult or) { final AtomicReference<Future<Channel>> sslready = new AtomicReference<>(); Bootstrap b = new Bootstrap(); b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) .handler(new ChannelInitializer<SocketChannel>() { @Override/*from ww w . jav a2s . c o m*/ public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (HyperSession.this.info.isSecurel()) { SslHandler sh = new SslHandler(HyperSession.this.sslfac.getClientEngine()); sslready.set(sh.handshakeFuture()); pipeline.addLast("ssl", sh); } pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); // TODO maybe //pipeline.addLast("deflater", new HttpContentCompressor()); pipeline.addLast("handler", handler); } }); or.info("Web Client connecting"); try { // must wait here to make sure we don't release connectLock too soon // we want channel init (above) to complete before we try connect again ChannelFuture f = b.connect(this.info.getAddress()).sync(); if (!f.isSuccess()) { or.error(1, "Web Client unable to successfully connect: " + f.cause()); } // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent // that lets wait for the handshake to be done for sure if (sslready.get() != null) { Future<Channel> sf = sslready.get().sync(); if (!sf.isSuccess()) { or.error(1, "Web Client unable to securely connect: " + sf.cause()); } } if (handler instanceof ClientHandler) ((ClientHandler) handler).waitConnect(); return f.channel(); } catch (InterruptedException x) { or.error(1, "Web Client interrupted while connecting: " + x); } catch (Exception x) { or.error(1, "Web Client unable to connect: " + x); } return null; }
From source file:divconq.api.HyperSession.java
License:Open Source License
public Channel allocateWsChannel(final ChannelHandler handler, OperationResult or) { final AtomicReference<Future<Channel>> sslready = new AtomicReference<>(); Bootstrap b = new Bootstrap(); b.group(Hub.instance.getEventLoopGroup()).option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) .channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override//from ww w. j ava 2 s . c o m public void initChannel(SocketChannel ch) throws Exception { HttpHeaders customHeaders = new DefaultHttpHeaders(); customHeaders.add("x-DivConq-Mode", Hub.instance.getResources().getMode()); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker( HyperSession.this.info.getUri(), WebSocketVersion.V13, null, false, customHeaders); ChannelPipeline pipeline = ch.pipeline(); if (HyperSession.this.info.isSecurel()) { SslHandler sh = new SslHandler(HyperSession.this.sslfac.getClientEngine()); sslready.set(sh.handshakeFuture()); pipeline.addLast("ssl", sh); } pipeline.addLast("http-codec", new HttpClientCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("ws-handler", new WebSocketClientProtocolHandler(handshaker)); pipeline.addLast("handler", handler); /* pipeline.addLast("handler", new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("read: " + msg); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { super.userEventTriggered(ctx, evt); Logger.debug("ue: " + evt); } }); */ } }); or.info("Web Client connecting"); try { // must wait here to make sure we don't release connectLock too soon // we want channel init (above) to complete before we try connect again ChannelFuture f = b.connect(this.info.getAddress()).sync(); if (!f.isSuccess()) { or.error(1, "Web Client unable to successfully connect: " + f.cause()); } // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent // that lets wait for the handshake to be done for sure if (sslready.get() != null) { Future<Channel> sf = sslready.get().sync(); if (!sf.isSuccess()) { or.error(1, "Web Client unable to securely connect: " + sf.cause()); } } if (handler instanceof ClientHandler) ((ClientHandler) handler).waitConnect(); return f.channel(); } catch (InterruptedException x) { or.error(1, "Web Client interrupted while connecting: " + x); } catch (Exception x) { or.error(1, "Web Client unable to connect: " + x); } return null; }
From source file:divconq.api.internal.DownloadHandler.java
License:Open Source License
public Channel allocateChannel(final HyperSession parent, OperationResult or) { final AtomicReference<Future<Channel>> sslready = new AtomicReference<>(); Bootstrap b = new Bootstrap(); b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) .handler(new ChannelInitializer<SocketChannel>() { @Override//from w w w.j a v a 2s . c om public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (parent.getInfo().isSecurel()) { SslHandler sh = new SslHandler(parent.getSsl().getClientEngine()); sslready.set(sh.handshakeFuture()); pipeline.addLast("ssl", sh); } pipeline.addLast("codec", new HttpClientCodec()); //pipeline.addLast("decoder", new HttpResponseDecoder()); //pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("handler", DownloadHandler.this); } }); or.info("Web Data Client connecting"); try { // must wait here to make sure we don't release connectLock too soon // we want chanel init (above) to complete before we try connect again ChannelFuture f = b.connect(parent.getInfo().getAddress()).sync(); if (!f.isSuccess()) { or.error(1, "Web Data Client unable to successfully connect: " + f.cause()); } // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent // that lets wait for the handshake to be done for sure if (sslready.get() != null) { Future<Channel> sf = sslready.get().sync(); if (!sf.isSuccess()) { or.error(1, "Web Data Client unable to securely connect: " + sf.cause()); } } return f.channel(); } catch (InterruptedException x) { or.error(1, "Web Data Client interrupted while connecting: " + x); } catch (Exception x) { or.error(1, "Web Data Client unable to connect: " + x); } return null; }
From source file:divconq.api.internal.UploadPostHandler.java
License:Open Source License
public Channel allocateChannel(final HyperSession parent, OperationResult or) { final AtomicReference<Future<Channel>> sslready = new AtomicReference<>(); Bootstrap b = new Bootstrap(); b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) .handler(new ChannelInitializer<SocketChannel>() { @Override/* w w w . j a v a 2 s.c om*/ public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (parent.getInfo().isSecurel()) { SslHandler sh = new SslHandler(parent.getSsl().getClientEngine()); sslready.set(sh.handshakeFuture()); pipeline.addLast("ssl", sh); } pipeline.addLast("codec", new HttpClientCodec()); // Remove the following line if you don't want automatic content decompression. //pipeline.addLast("inflater", new HttpContentDecompressor()); // to be used since huge file transfer pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // so we can get the upload response (200 or not) pipeline.addLast("handler", UploadPostHandler.this); } }); System.out.println("Web Data Client connecting"); try { // must wait here to make sure we don't release connectLock too soon // we want chanel init (above) to complete before we try connect again ChannelFuture f = b.connect(parent.getInfo().getAddress()).sync(); if (!f.isSuccess()) { or.error(1, "Web Client unable to successfully connect: " + f.cause()); System.out.println("Web Client unable to successfully connect: " + f.cause()); } // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent // that lets wait for the handshake to be done for sure if (sslready.get() != null) { Future<Channel> sf = sslready.get().sync(); if (!sf.isSuccess()) { or.error(1, "Web Client unable to securely connect: " + sf.cause()); System.out.println("Web Client unable to securely connect: " + sf.cause()); } } return f.channel(); } catch (InterruptedException x) { or.error(1, "Web Client interrupted while connecting: " + x); System.out.println("Web Client interrupted while connecting: " + x); } catch (Exception x) { or.error(1, "Web Client unable to connect: " + x); System.out.println("Web Client unable to connect: " + x); } return null; }
From source file:divconq.api.internal.UploadPutHandler.java
License:Open Source License
public Channel allocateChannel(final HyperSession parent, OperationResult or) { final AtomicReference<Future<Channel>> sslready = new AtomicReference<>(); Bootstrap b = new Bootstrap(); b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) .handler(new ChannelInitializer<SocketChannel>() { @Override//from w w w .j a v a 2 s . co m public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (parent.getInfo().isSecurel()) { SslHandler sh = new SslHandler(parent.getSsl().getClientEngine()); sslready.set(sh.handshakeFuture()); pipeline.addLast("ssl", sh); } pipeline.addLast("codec", new HttpClientCodec()); // so we can get the upload response (200 or not) pipeline.addLast("handler", UploadPutHandler.this); } }); or.info("Web Data Client connecting"); try { // must wait here to make sure we don't release connectLock too soon // we want chanel init (above) to complete before we try connect again ChannelFuture f = b.connect(parent.getInfo().getAddress()).sync(); if (!f.isSuccess()) { or.error(1, "Web Client unable to successfully connect: " + f.cause()); } // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent // that lets wait for the handshake to be done for sure if (sslready.get() != null) { Future<Channel> sf = sslready.get().sync(); if (!sf.isSuccess()) { or.error(1, "Web Client unable to securely connect: " + sf.cause()); } } return f.channel(); } catch (InterruptedException x) { or.error(1, "Web Client interrupted while connecting: " + x); } catch (Exception x) { or.error(1, "Web Client unable to connect: " + x); } return null; }
From source file:divconq.bus.Bus.java
License:Open Source License
public void connect() { // never try to connect until init has run if (Hub.instance.isStopping()) return;/*from w ww. j a v a2s.c o m*/ // if connect method is already running then skip - it will try again later if (!this.connectLock.tryLock()) return; try { // ========================================================================== // Add client connections when not enough // ========================================================================== for (final SocketInfo info : this.connectors.values()) { HubRouter router = this.allocateOrGetHub(info.getHubId(), info.isGateway()); if (router.isLocal()) continue; // ------------------------------------------------- // message port // ------------------------------------------------- int conncount = router.getCountSessions(info); // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls) if (conncount < info.getCount()) { Bootstrap b = new Bootstrap(); b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (info.isUseSsl()) pipeline.addLast("ssl", new SslHandler(SslContextFactory.getClientEngine())); pipeline.addLast("http-codec", new HttpClientCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); // TODO is this too small? pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config pipeline.addLast("ws-handler", new ClientHandler(info)); } }); Logger.debug("dcBus Client connecting"); try { // must wait here to make sure we don't release connectLock too soon // we want channel init (above) to complete before we try connect again b.connect(info.getAddress()).sync(); } catch (InterruptedException x) { Logger.warn("dcBus Client interrupted while connecting: " + x); } catch (Exception x) { Logger.debug("dcBus Client unable to connect: " + x); } } // ------------------------------------------------- // stream port // ------------------------------------------------- conncount = router.getCountStreamSessions(info); // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls) if (conncount < info.getStreamCount()) { Bootstrap b = new Bootstrap(); b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (info.isUseSsl()) pipeline.addLast("ssl", new SslHandler(SslContextFactory.getClientEngine())); // TODO consider compression pipeline.addLast("decoder", new StreamDecoder()); pipeline.addLast("encoder", new StreamEncoder()); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config pipeline.addLast("handler", new StreamHandler(info, false)); } }); Logger.debug("dcBus Client stream connecting"); try { // must wait here to make sure we don't release connectLock too soon // we want chanel init (above) to complete before we try connect again b.connect(info.getStreamAddress()).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture cf) throws Exception { if (!cf.isSuccess()) { Logger.debug("dcBus Stream unable to connect: " + cf.cause()); return; } // client starts the HELLO thing once connected! StreamMessage icmd = Hub.instance.getBus().getLocalHub() .buildStreamHello(info.getHubId()); cf.channel().writeAndFlush(icmd); } }).sync(); } catch (InterruptedException x) { Logger.warn("dcBus Client stream interrupted while connecting: " + x); } catch (Exception x) { Logger.debug("dcBus Client stream unable to connect: " + x); } } } // ========================================================================== // Add server binding when missing // ========================================================================== for (final SocketInfo info : this.listeners) { // only if not currently bound if (this.activelisteners.containsKey(info)) continue; // ------------------------------------------------- // message port // ------------------------------------------------- ServerBootstrap b = new ServerBootstrap(); b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) //.option(ChannelOption.SO_BACKLOG, 125) // this is probably not needed but serves as note to research .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (info.isUseSsl()) pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine())); pipeline.addLast("codec-http", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config pipeline.addLast("handler", new ServerHandler(info)); } }); try { // must wait here, both to keep the activelisteners listeners up to date // but also to make sure we don't release connectLock too soon ChannelFuture bfuture = b.bind(info.getAddress()).sync(); if (bfuture.isSuccess()) { Logger.info("dcBus Message Server listening - now listening for dcMessages on TCP port " + info.getPort()); this.activelisteners.put(info, bfuture.channel()); } else Logger.error("dcBus Server unable to bind: " + bfuture.cause()); } catch (InterruptedException x) { Logger.warn("dcBus Server interrupted while binding: " + x); } catch (Exception x) { Logger.error("dcBus Server unable to bind: " + x); } // ------------------------------------------------- // stream port // ------------------------------------------------- b = new ServerBootstrap(); b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) //.option(ChannelOption.SO_BACKLOG, 125) // this is probably not needed but serves as note to research .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (info.isUseSsl()) pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine())); // TODO consider compression pipeline.addLast("decoder", new StreamDecoder()); pipeline.addLast("encoder", new StreamEncoder()); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config pipeline.addLast("handler", new StreamHandler(info, true)); } }); try { // must wait here, both to keep the activelisteners listeners up to date // but also to make sure we don't release connectLock too soon ChannelFuture bfuture = b.bind(info.getStreamAddress()).sync(); if (bfuture.isSuccess()) { Logger.info("dcBus Stream Server listening - now listening for dcStreams on TCP port " + info.getPort()); this.activestreamlisteners.put(info, bfuture.channel()); } else Logger.error("dcBus Stream Server unable to bind: " + bfuture.cause()); } catch (InterruptedException x) { Logger.warn("dcBus Stream Server interrupted while binding: " + x); } catch (Exception x) { Logger.error("dcBus Stream Server unable to bind: " + x); } } // ========================================================================== // Remove server binding as needed // ========================================================================== for (final SocketInfo info : this.activelisteners.keySet()) { // all is well if in the listeners list if (this.listeners.contains(info)) continue; // otherwise we don't want to bind anymore this.stopSocketListener(info); } } finally { this.connectLock.unlock(); } }
From source file:divconq.ctp.net.CtpServices.java
License:Open Source License
public void connect() { // never try to connect until init has run if (Hub.instance.isStopping()) return;/*from ww w .j a va 2 s . co m*/ // if connect method is already running then skip - it will try again later if (!this.connectLock.tryLock()) return; try { // ========================================================================== // Add server binding when missing // ========================================================================== for (SocketInfo info : this.listeners) { // only if not currently bound if (this.activelisteners.containsKey(info)) continue; // ------------------------------------------------- // stream port // ------------------------------------------------- ServerBootstrap b = new ServerBootstrap().group(Hub.instance.getEventLoopGroup()) .channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) //.option(ChannelOption.SO_BACKLOG, 125) // this is probably not needed but serves as note to research .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (info.isUseSsl()) pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine())); // TODO this should be the external SSL not the BUS one pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(45)); // TODO config //pipeline.addLast("logger", new LoggingHandler(LogLevel.INFO)); // start as guest until authenticated CtpAdapter adapter = new CtpAdapter(OperationContext.allocateGuest()); adapter.setHandler(new CtpsHandler()); pipeline.addLast("ctp", new CtpHandler(adapter, true)); } }); try { // must wait here, both to keep the activelisteners listeners up to date // and also to make sure we don't release connectLock too soon ChannelFuture bfuture = b.bind(info.getAddress()).sync(); if (bfuture.isSuccess()) { Logger.info("dcCtp Server listening"); this.activelisteners.put(info, bfuture.channel()); } else Logger.error("dcCtp Server unable to bind: " + bfuture.cause()); } catch (InterruptedException x) { Logger.warn("dcCtp Server interrupted while binding: " + x); } catch (Exception x) { Logger.error("dcCtp Server unable to bind: " + x); } } // ========================================================================== // Remove server binding as needed // ========================================================================== for (final SocketInfo info : this.activelisteners.keySet()) { // all is well if in the listeners list if (this.listeners.contains(info)) continue; // otherwise we don't want to bind anymore this.stopSocketListener(info); } } finally { this.connectLock.unlock(); } }
From source file:divconq.web.WebModule.java
License:Open Source License
public void goOnline() { this.listenlock.lock(); try {/*w w w. j ava2 s.c o m*/ // don't try if already in online mode if (this.activelisteners.size() > 0) return; // typically we should have an extension, unless we are supporting RPC only // TODO if (WebSiteManager.instance.getDefaultExtension() == null) // log.warn(0, "No default extension for web server"); for (final XElement httpconfig : this.config.selectAll("HttpListener")) { final boolean secure = "True".equals(httpconfig.getAttribute("Secure")); int httpport = (int) StringUtil.parseInt(httpconfig.getAttribute("Port"), secure ? 443 : 80); // ------------------------------------------------- // message port // ------------------------------------------------- ServerBootstrap b = new ServerBootstrap(); // TODO consider using shared EventLoopGroup // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#25.0 b.group(Hub.instance.getEventLoopGroup()).channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) //.option(ChannelOption.SO_BACKLOG, 125) // this is probably not needed but serves as note to research .option(ChannelOption.TCP_NODELAY, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secure) { SniHandler ssl = new SniHandler(WebModule.this.siteman); //SslHandler ssl = new SslHandler(WebModule.this.siteman.findSslContextFactory("root").getServerEngine()); pipeline.addLast("ssl", ssl); } //pipeline.addLast("codec-http", new HttpServerCodec()); //pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, 262144)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // TODO maybe - but currently we selectively compress files which is more efficient // this can also be a cached & compressed response that way //pipeline.addLast("deflater", new HttpContentCompressor()); pipeline.addLast("handler", new ServerHandler(httpconfig, WebModule.this.siteman)); } }); try { // must wait here, both to keep the activelisteners listeners up to date // but also to make sure we don't release connectLock too soon ChannelFuture bfuture = b.bind(httpport).sync(); if (bfuture.isSuccess()) { Logger.info("Web Server listening - now listening for HTTP on TCP port " + httpport); this.activelisteners.put(httpport, bfuture.channel()); } else Logger.error("Web Server unable to bind: " + bfuture.cause()); } catch (InterruptedException x) { Logger.error("Web Server interrupted while binding: " + x); } catch (Exception x) { Logger.error("Web Server errored while binding: " + x); } } } finally { this.listenlock.unlock(); } this.siteman.online(); //for (IWebExtension ext : WebSiteManager.instance.extensions.values()) // ext.online(); }
From source file:dorkbox.network.Client.java
License:Apache License
/** * Starts a REMOTE <b>only</b> client, which will connect to the specified host using the specified Connections Options *//*w ww .j a va 2 s.c om*/ @SuppressWarnings("AutoBoxing") public Client(final Configuration config) throws SecurityException { super(config); String threadName = Client.class.getSimpleName(); this.config = config; boolean hostConfigured = (config.tcpPort > 0 || config.udpPort > 0) && config.host != null; boolean isLocalChannel = config.localChannelName != null; if (isLocalChannel && hostConfigured) { String msg = threadName + " Local channel use and TCP/UDP use are MUTUALLY exclusive. Unable to determine what to do."; logger.error(msg); throw new IllegalArgumentException(msg); } localChannelName = config.localChannelName; hostName = config.host; Bootstrap localBootstrap = null; Bootstrap tcpBootstrap = null; Bootstrap udpBootstrap = null; if (config.localChannelName != null) { localBootstrap = new Bootstrap(); } if (config.tcpPort > 0 || config.udpPort > 0) { if (config.host == null) { throw new IllegalArgumentException("You must define what host you want to connect to."); } if (config.host.equals("0.0.0.0")) { throw new IllegalArgumentException( "You cannot connect to 0.0.0.0, you must define what host you want to connect to."); } } if (config.tcpPort > 0) { tcpBootstrap = new Bootstrap(); } if (config.udpPort > 0) { udpBootstrap = new Bootstrap(); } if (localBootstrap == null && tcpBootstrap == null && udpBootstrap == null) { throw new IllegalArgumentException( "You must define how you want to connect, either LOCAL channel name, TCP port, or UDP port"); } if (config.localChannelName != null) { // no networked bootstraps. LOCAL connection only bootstraps.add(new BootstrapWrapper("LOCAL", config.localChannelName, -1, localBootstrap)); localBootstrap.group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS")).channel(LocalChannel.class) .remoteAddress(new LocalAddress(config.localChannelName)) .handler(new RegistrationLocalHandlerClient(threadName, registrationWrapper)); } EventLoopGroup workerEventLoop = null; if (tcpBootstrap != null || udpBootstrap != null) { workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName); } if (tcpBootstrap != null) { bootstraps.add(new BootstrapWrapper("TCP", config.host, config.tcpPort, tcpBootstrap)); if (OS.isAndroid()) { // android ONLY supports OIO (not NIO) tcpBootstrap.channel(OioSocketChannel.class); } else if (OS.isLinux() && NativeLibrary.isAvailable()) { // epoll network stack is MUCH faster (but only on linux) tcpBootstrap.channel(EpollSocketChannel.class); } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) { // KQueue network stack is MUCH faster (but only on macosx) tcpBootstrap.channel(KQueueSocketChannel.class); } else { tcpBootstrap.channel(NioSocketChannel.class); } tcpBootstrap.group(newEventLoop(1, threadName + "-TCP-BOSS")) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH)) .remoteAddress(config.host, config.tcpPort).handler(new RegistrationRemoteHandlerClientTCP( threadName, registrationWrapper, workerEventLoop)); // android screws up on this!! tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).option(ChannelOption.SO_KEEPALIVE, true); } if (udpBootstrap != null) { bootstraps.add(new BootstrapWrapper("UDP", config.host, config.udpPort, udpBootstrap)); if (OS.isAndroid()) { // android ONLY supports OIO (not NIO) udpBootstrap.channel(OioDatagramChannel.class); } else if (OS.isLinux() && NativeLibrary.isAvailable()) { // epoll network stack is MUCH faster (but only on linux) udpBootstrap.channel(EpollDatagramChannel.class); } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) { // KQueue network stack is MUCH faster (but only on macosx) udpBootstrap.channel(KQueueDatagramChannel.class); } else { udpBootstrap.channel(NioDatagramChannel.class); } udpBootstrap.group(newEventLoop(1, threadName + "-UDP-BOSS")) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // Netty4 has a default of 2048 bytes as upper limit for datagram packets. .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(EndPoint.udpMaxSize)) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH)) .localAddress(new InetSocketAddress(0)) // bind to wildcard .remoteAddress(new InetSocketAddress(config.host, config.udpPort)) .handler(new RegistrationRemoteHandlerClientUDP(threadName, registrationWrapper, workerEventLoop)); // Enable to READ and WRITE MULTICAST data (ie, 192.168.1.0) // in order to WRITE: write as normal, just make sure it ends in .255 // in order to LISTEN: // InetAddress group = InetAddress.getByName("203.0.113.0"); // NioDatagramChannel.joinGroup(group); // THEN once done // NioDatagramChannel.leaveGroup(group), close the socket udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize); } }