public static void main(String[] args) { Executor executor = Executors.newFixedThreadPool(200); ServerBootstrap bootstrap = new ServerBootstrap(); EventLoopGroup bossGroup = new OioEventLoopGroup(); EventLoopGroup childGroup = new OioEventLoopGroup(); bootstrap.group(bossGroup, childGroup); bootstrap.channel(OioServerSocketChannel.class); bootstrap.childHandler(new RPCServerSessionPipelineFactory( new RPCServerMixinPipelineFactory(executor, childGroup))); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); }
/** * Instantiates a new controller. * * @param wrappedJavaProcess * the wrapped java process */ public JVMController(WrappedProcess wrappedJavaProcess) { super(wrappedJavaProcess); _bossGroup = new OioEventLoopGroup(); _workerGroup = new OioEventLoopGroup(); ControllerPipelineFactory pipelineFactory = new ControllerPipelineFactory( this); setDebug(((WrappedJavaProcess)wrappedJavaProcess).getDebug()); pipelineFactory.setDebug(_debug > 2); _acceptor = new ServerBootstrap().group(_bossGroup, _workerGroup) .channel(OioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_BACKLOG, 128) .childHandler(pipelineFactory); }
public List<BootstrapFactory<ServerBootstrap>> serverSocket() { return Arrays.asList( new BootstrapFactory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) .channel(NioServerSocketChannel.class); } }, new BootstrapFactory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { return new ServerBootstrap().group(oioBossGroup, oioWorkerGroup) .channel(OioServerSocketChannel.class) .option(ChannelOption.SO_TIMEOUT, OIO_SO_TIMEOUT); } } ); }
@Test public void testTooManyAcceptedChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap(); sb.channel(OioServerSocketChannel.class); sb.group(g); sb.childHandler(new ChannelInboundHandlerAdapter()); ChannelFuture f1 = sb.bind(0); f1.sync(); Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort()); assertThat(s.getInputStream().read(), is(-1)); s.close(); g.shutdownGracefully(); }
public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new OioEventLoopGroup(1); EventLoopGroup workerGroup = new OioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(OioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new EchoServerHandler()); } }); ChannelFuture f = b.bind(8888).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
static List<Factory<ServerBootstrap>> serverSocket() { List<Factory<ServerBootstrap>> list = new ArrayList<Factory<ServerBootstrap>>(); // Make the list of ServerBootstrap factories. list.add(new Factory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup) .channel(NioServerSocketChannel.class); } }); list.add(new Factory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { return new ServerBootstrap().group(oioBossGroup, oioWorkerGroup) .channel(OioServerSocketChannel.class); } }); return list; }
public static ServerBootstrap createServerBootstrap(ChannelType channelType,boolean isUDP) throws UnsupportedOperationException { ServerBootstrap serverBootstrap = new ServerBootstrap(); switch (channelType) { case NIO: serverBootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()); serverBootstrap.channel(NioServerSocketChannel.class); return serverBootstrap; case OIO: serverBootstrap.group(new OioEventLoopGroup(), new OioEventLoopGroup()); serverBootstrap.channel(OioServerSocketChannel.class); return serverBootstrap; default: throw new UnsupportedOperationException("Failed to create ServerBootstrap, " + channelType + " not supported!"); } }
public void start() { apiBootstrap = new ServerBootstrap(); try { // the hub will only have a few connections, so OIO is likely to be faster than NIO in this case! ThreadFactory threadFactory = new NamedThreadFactory("kha-rest-api"); EventLoopGroup commonGroup = new OioEventLoopGroup(0, threadFactory); apiBootstrap.group(commonGroup, commonGroup) .channel(OioServerSocketChannel.class) .localAddress(port) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(channelInitializer); apiBootstrap.bind(); // ChannelFuture f = apiBootstrap.bind().sync(); LOGGER.info("REST API available on http://{}:{}", InetAddress.getLocalHost().getCanonicalHostName(), port); LOGGER.info("WebSockets API available on ws://{}:{}", InetAddress.getLocalHost().getCanonicalHostName(), port); // f.channel().closeFuture().sync(); } catch (Exception e) { LOGGER.error("Can't start API server", e); } }
@Test public void testTooManyAcceptedChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap(); sb.channel(OioServerSocketChannel.class); sb.group(g); sb.childHandler(new ChannelHandlerAdapter()); ChannelFuture f1 = sb.bind(0); f1.sync(); Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort()); assertThat(s.getInputStream().read(), is(-1)); s.close(); g.shutdownGracefully(); }
/** * Returns a server socket channel class suitable for specified event loop group. * * @param eventLoopGroup the event loop group for which to identify an appropriate socket channel class; must not * be {@code null} * * @return a server socket channel class suitable for use with the given event loop group * * @throws IllegalArgumentException in case of null or unrecognized event loop group */ @SuppressWarnings("unchecked") static Class<? extends ServerChannel> getServerSocketChannelClass(final EventLoopGroup eventLoopGroup) { Objects.requireNonNull(eventLoopGroup); final Class<? extends ServerChannel> serverSocketChannelClass; if (eventLoopGroup instanceof NioEventLoopGroup) { serverSocketChannelClass = NioServerSocketChannel.class; } else if (eventLoopGroup instanceof OioEventLoopGroup) { serverSocketChannelClass = OioServerSocketChannel.class; } else if (EPOLL_EVENT_LOOP_GROUP_CLASS.equals(eventLoopGroup.getClass().getName())) { serverSocketChannelClass = (Class<? extends ServerChannel>) loadSocketChannelClass(EPOLL_SERVER_SOCKET_CHANNEL_CLASS); } else if (KQUEUE_EVENT_LOOP_GROUP_CLASS.equals(eventLoopGroup.getClass().getName())) { serverSocketChannelClass = (Class<? extends ServerChannel>) loadSocketChannelClass(KQUEUE_SERVER_SOCKET_CHANNEL_CLASS); } else { throw new IllegalArgumentException("Could not find server socket class for event loop group class: " + eventLoopGroup.getClass().getName()); } return serverSocketChannelClass; }
public void server(int port) throws Exception { final ByteBuf buf = Unpooled.unreleasableBuffer( Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8"))); EventLoopGroup group = new OioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(OioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE); } }); } }); ChannelFuture f = b.bind().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
@Test public void testTooManyServerChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap b = new ServerBootstrap(); b.channel(OioServerSocketChannel.class); b.group(g); b.childHandler(new ChannelInboundHandlerAdapter()); ChannelFuture f1 = b.bind(0); f1.sync(); ChannelFuture f2 = b.bind(0); f2.await(); assertThat(f2.cause(), is(instanceOf(ChannelException.class))); assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels")); final CountDownLatch notified = new CountDownLatch(1); f2.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { notified.countDown(); } }); notified.await(); g.shutdownGracefully(); }
@Test public void testTooManyClientChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap(); sb.channel(OioServerSocketChannel.class); sb.group(g); sb.childHandler(new ChannelInboundHandlerAdapter()); ChannelFuture f1 = sb.bind(0); f1.sync(); Bootstrap cb = new Bootstrap(); cb.channel(OioSocketChannel.class); cb.group(g); cb.handler(new ChannelInboundHandlerAdapter()); ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort()); f2.await(); assertThat(f2.cause(), is(instanceOf(ChannelException.class))); assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels")); final CountDownLatch notified = new CountDownLatch(1); f2.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { notified.countDown(); } }); notified.await(); g.shutdownGracefully(); }
public void serve(int port) throws IOException, InterruptedException { final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8"))); //1. Create ServerBootstrap to allow bootstrap to server instance ServerBootstrap bootstrap = new ServerBootstrap(); //2. Use OioEventLoopGroup Ito allow blocking mode (Old-IO) EventLoopGroup group = new OioEventLoopGroup(); try { bootstrap.group(group) .channel(OioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { //3. Specify ChannelInitializer that will be called for each accepted connection @Override protected void initChannel(SocketChannel ch) throws Exception { //4. Add ChannelHandler to intercept events and allow to react on them ch.pipeline().addLast(new ChannelHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { //5. Write message to client and add ChannelFutureListener to close connection once message written ctx.write(buf.duplicate()).addListener(ChannelFutureListener.CLOSE); } }); } }); //6. Bind server to accept connections ChannelFuture future = bootstrap.bind().sync(); future.channel().closeFuture().sync(); } finally { //7. Release all resources group.shutdownGracefully().sync(); } }
public void start() { apiBootstrap = new ServerBootstrap(); ThreadFactory threadFactory = new NamedThreadFactory("kha-webapp"); EventLoopGroup commonGroup = new OioEventLoopGroup(0, threadFactory); try { // the hub will only have a few connections, so OIO is likely to be faster than NIO in this case! apiBootstrap.group(commonGroup, commonGroup) .channel(OioServerSocketChannel.class) .localAddress(port) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-request-decoder", new HttpRequestDecoder()); pipeline.addLast("http-object-aggregator", new HttpObjectAggregator(1048576)); pipeline.addLast("http-response-encoder", new HttpResponseEncoder()); // pipeline.addLast("deflater", new HttpContentDecompressor()); // pipeline.addLast("inflater", new HttpContentCompressor()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("cors", new CorsHandler(corsConfig)); pipeline.addLast("file-handler", new HttpStaticFileServerHandler(hubSiteDirectory, true)); } }); ChannelFuture f = apiBootstrap.bind().sync(); LOGGER.info("WebApp available on http://{}:{}", InetAddress.getLocalHost().getCanonicalHostName(), port); f.channel().closeFuture().sync(); } catch (Exception e) { LOGGER.error("Can't start WebApp server", e); } }
public void start() { apiBootstrap = new ServerBootstrap(); parentGroup = new OioEventLoopGroup(); childGroup = new OioEventLoopGroup(); try { // the cloudPlatform will only have a few connections, so OIO is likely to be faster than NIO in this case! apiBootstrap.group(parentGroup, childGroup) .channel(OioServerSocketChannel.class) .localAddress(port) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-request-decoder", new HttpRequestDecoder()); // pipeline.addLast("deflater", new HttpContentDecompressor()); pipeline.addLast("http-object-aggregator", new HttpObjectAggregator(1048576)); pipeline.addLast("http-response-encoder", new HttpResponseEncoder()); // pipeline.addLast("inflater", new HttpContentCompressor()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("file-handler", new HttpStaticFileServerHandler(System.getProperty("user.dir"), true)); } }); ChannelFuture f = apiBootstrap.bind().sync(); LOGGER.info("WebApp available on port {}.", port); f.channel().closeFuture().sync(); } catch (Exception e) { LOGGER.error("Can't start WebApp server", e); } }
@Test public void testTooManyServerChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap b = new ServerBootstrap(); b.channel(OioServerSocketChannel.class); b.group(g); b.childHandler(new ChannelHandlerAdapter()); ChannelFuture f1 = b.bind(0); f1.sync(); ChannelFuture f2 = b.bind(0); f2.await(); assertThat(f2.cause(), is(instanceOf(ChannelException.class))); assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels")); final CountDownLatch notified = new CountDownLatch(1); f2.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { notified.countDown(); } }); notified.await(); g.shutdownGracefully(); }
@Test public void testTooManyClientChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap(); sb.channel(OioServerSocketChannel.class); sb.group(g); sb.childHandler(new ChannelHandlerAdapter()); ChannelFuture f1 = sb.bind(0); f1.sync(); Bootstrap cb = new Bootstrap(); cb.channel(OioSocketChannel.class); cb.group(g); cb.handler(new ChannelHandlerAdapter()); ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort()); f2.await(); assertThat(f2.cause(), is(instanceOf(ChannelException.class))); assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels")); final CountDownLatch notified = new CountDownLatch(1); f2.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { notified.countDown(); } }); notified.await(); g.shutdownGracefully(); }
/** * Initializes a new TCPConnectionManager. * * @param serverConfig * a configuration to use for initializing * @return the new ConnectionManager */ private ConnectionManager initializeConnectionManager(final AddressBasedServerConfig serverConfig) { LOGGER.entry(); final EventLoopGroup applicationEventLoopGroup = new OioEventLoopGroup(); final EventLoopGroup networkEventLoopGroup = new OioEventLoopGroup(); eventExecutorGroups.add(applicationEventLoopGroup); eventExecutorGroups.add(networkEventLoopGroup); final ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(networkEventLoopGroup, applicationEventLoopGroup); serverBootstrap.channel(OioServerSocketChannel.class); final ServerBootstrapChannelFactory serverChannelFactory = new ServerBootstrapChannelFactory(serverBootstrap); final Bootstrap clientBootstrap = new Bootstrap(); clientBootstrap.group(applicationEventLoopGroup); clientBootstrap.channel(OioSocketChannel.class); final ClientBootstrapChannelFactory clientChannelFactory = new ClientBootstrapChannelFactory(clientBootstrap); final TCPConnectionManager connectionManager = new TCPConnectionManager(serverChannelFactory, clientChannelFactory, scheduledExecutorService, serverConfig.getModuleID()); new TCPProtocol().initialize(connectionManager); for (final InetSocketAddress address : serverConfig.getListenAddresses()) { connectionManager.startListening(address); } return LOGGER.exit(connectionManager); }
public RpcServer(OioEventLoopGroup eventLoopGroup, EventExecutorGroup eventExecutor, @Assisted SocketAddress address) { this(eventLoopGroup, eventExecutor, OioServerSocketChannel.class, address); }
public AHessianJmxServer(MBeanServer mbeanServer, String ipFilter, String serviceDiscoveryName, int port, InternalLogger logger, int debug, InetAddress address) throws Exception { // InternalLoggerFactory.setDefaultFactory(new SimpleLoggerFactory()); ChannelPipelineFactoryBuilder builder = new ChannelPipelineFactoryBuilder() .serializerFactory(new JmxSerializerFactory()) .rpcServiceInterface(MBeanServerConnection.class) .rpcServerService(mbeanServer).serviceThreads(10) .ipFilter(ipFilter); if (debug > 2) builder.debug(); Set<String> channelOptions = new HashSet(); // channelOptions.add("SO_REUSE"); channelOptions.add("TCP_NODELAY"); int serverPort = port; DefaultServer server = new DefaultServer(OioServerSocketChannel.class, builder, channelOptions, serverPort, address); server.start(); Channel channel = server.getChannel(); Executor executor = Executors.newCachedThreadPool(); if (serverPort == 0) serverPort = ((InetSocketAddress) channel.localAddress()).getPort(); if (debug > 2 && logger != null) logger.info("ahessian jmx service bound to port " + serverPort); DiscoveryServer discovery = new DiscoveryServer(); discovery.setDebug(debug > 2); discovery.setLogger(logger); // allow discovery only from localhost. other computers will be ignored discovery.setIpSet(new IpFilterRuleList("+n:localhost, -n:*")); discovery.setName(serviceDiscoveryName); discovery.setPort(serverPort); discovery.init(); }
/** * {@inheritDoc} */ @Override public synchronized boolean init() { if(this.running.get()) { return true; } // create bootstrap Class<? extends ServerChannel> channelType; if(useNio) { this.workerGroup = new NioEventLoopGroup(); this.bossGroup = new NioEventLoopGroup(); channelType = NioServerSocketChannel.class; } else { this.workerGroup = new OioEventLoopGroup(); this.bossGroup = new OioEventLoopGroup(); channelType = OioServerSocketChannel.class; } bootstrap = new ServerBootstrap(); bootstrap.group(this.bossGroup, this.workerGroup) .option(ChannelOption.SO_SNDBUF, this.sendBufferSize) .option(ChannelOption.SO_RCVBUF, this.receiveBufferSize) .channel(channelType) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<Channel>() { // is used to initialize the ChannelPipeline @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("encoder", new RtspEncoder()); pipeline.addLast("decoder", new RtspDecoder()); pipeline.addLast("aggregator", new HttpObjectAggregator(64*1024)); pipeline.addLast("handler", new RtspHandler(SimpleRtspSession.this)); } }); // create channel try { ChannelFuture future = bootstrap.bind(this.localAddress); this.channel = future.sync().channel(); // wait for future to complete and retrieve channel } catch (Exception e) { LOG.error("Failed to bind RTSP channel for session with id " + this.id, e); this.workerGroup.shutdownGracefully(); this.bossGroup.shutdownGracefully(); this.workerGroup.terminationFuture().syncUninterruptibly(); this.bossGroup.terminationFuture().syncUninterruptibly(); return false; } LOG.debug("RTSP channel bound for RtspSession with id {}.", this.id); this.running.set(true); return true; }
@Override protected void configureBootstrap() { serverBootstrap.group(new OioEventLoopGroup(workerCount)) .channel(OioServerSocketChannel.class); }
@Override protected void configureBootstrap() { _nettyBootstrap.group(new OioEventLoopGroup(workerCount)) .channel(OioServerSocketChannel.class); }
public static ServerBootstrap serverBootstrap(EventLoopGroup group) { ServerBootstrap bootstrap = new ServerBootstrap().group(group).channel(group instanceof NioEventLoopGroup ? NioServerSocketChannel.class : OioServerSocketChannel.class); bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); return bootstrap; }