List of usage examples for io.netty.bootstrap ServerBootstrap childOption
public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value)
From source file:me.bigteddy98.movingmotd.Main.java
License:Open Source License
@Override public void run() { nettyThreadGroup = new ThreadGroup(Thread.currentThread().getThreadGroup(), "NettyThreadGroup"); new Thread(this.nettyThreadGroup, new Runnable() { @Override//w w w . j a va 2s .com public void run() { final ThreadGroup group = new ThreadGroup(Main.this.nettyThreadGroup, "PortListener"); EventLoopGroup bossGroup = new NioEventLoopGroup(MAX_NETTY_BOSS_THREADS, new ThreadFactory() { private int counter = 0; private String newName = group.getName() + "\\nettyboss"; @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, newName + "\\" + counter++); t.setPriority(Thread.NORM_PRIORITY - 1); t.setDaemon(true); return t; } }); EventLoopGroup workerGroup = new NioEventLoopGroup(MAX_NETTY_WORKER_THREADS, new ThreadFactory() { private int counter = 0; private String newName = group.getName() + "\\nettyworker"; @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, newName + "\\" + counter++); t.setPriority(Thread.NORM_PRIORITY - 1); t.setDaemon(true); return t; } }); try { ServerBootstrap bootstrab = new ServerBootstrap(); bootstrab.group(bossGroup, workerGroup); bootstrab.channel(NioServerSocketChannel.class); bootstrab.childHandler(new ClientSideConnectionInitialization("localhost", toPort)); bootstrab.childOption(ChannelOption.AUTO_READ, false); bootstrab.bind(fromPort).sync().channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }).start(); }
From source file:me.bigteddy98.slimeportal.Main.java
License:Open Source License
public void run() throws Exception { SlimeLogger.info("Starting " + NAME + " version " + VERSION + " developed by " + AUTHOR + "!"); SlimeLogger.info(//from w ww.ja v a2 s . c om "Starting server process using commandline " + Arrays.asList(processBuilder).toString() + "..."); ProcessBuilder builder = new ProcessBuilder(processBuilder); builder.redirectErrorStream(true); this.serverProcess = builder.start(); this.processPrintWriter = new PrintWriter(this.serverProcess.getOutputStream()); SlimeLogger.info("Server process started."); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { serverProcess.destroy(); } })); new Thread(new Runnable() { @Override public void run() { try (InputStream r = serverProcess.getInputStream()) { StringBuilder tmp = new StringBuilder(); byte[] consoleOutput = new byte[1024]; int read; while ((read = r.read(consoleOutput)) != -1) { String consoleLog = new String(consoleOutput, 0, read); String[] c = consoleLog.split("\n", -1); if (c.length != 0) { if (c.length == 1) { tmp.append(c[0]); } else { for (int i = 0; i < c.length - 1; i++) { tmp.append(c[i]); SlimeLogger.info(tmp.toString()); tmp.setLength(0); } tmp.append(c[c.length - 1]); } } } } catch (IOException e) { e.printStackTrace(); } SlimeLogger.warn("Server thread ended!"); System.exit(0); } }, "Server Output Reader").start(); new Thread(new Runnable() { @Override public void run() { try (Scanner in = new Scanner(System.in)) { while (in.hasNextLine()) { String newLine = in.nextLine(); executeCommand(newLine); } } SlimeLogger.warn("COMMAND LOOP ENDED, this shouldn't happen!"); } }, "CommandReader").start(); final ThreadGroup nettyListeners = new ThreadGroup(Thread.currentThread().getThreadGroup(), "Netty Listeners"); new Thread(nettyListeners, new Runnable() { @Override public void run() { SlimeLogger.info("Started Netty Server at port " + fromPort + "..."); final ThreadGroup group = new ThreadGroup(nettyListeners, "Listener-" + toPort); EventLoopGroup bossGroup = new NioEventLoopGroup(MAX_NETTY_BOSS_THREADS, new ThreadFactory() { private int threadCount = 0; private String newName = group.getName() + "\\boss"; @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, newName + "\\" + threadCount++); t.setPriority(Thread.NORM_PRIORITY - 1); t.setDaemon(true); return t; } }); EventLoopGroup workerGroup = new NioEventLoopGroup(MAX_NETTY_WORKER_THREADS, new ThreadFactory() { private int threadCount = 0; private String newName = group.getName() + "\\worker"; @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, newName + "\\" + threadCount++); t.setPriority(Thread.NORM_PRIORITY - 1); t.setDaemon(true); return t; } }); try { ServerBootstrap bootstrab = new ServerBootstrap(); bootstrab.group(bossGroup, workerGroup); bootstrab.channel(NioServerSocketChannel.class); bootstrab.childHandler(new ClientboundConnectionInitializer("localhost", toPort)); bootstrab.childOption(ChannelOption.AUTO_READ, false); bootstrab.bind(fromPort).sync().channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }).start(); }
From source file:me.ferrybig.p2pnetwork.Main.java
private void startIncomingConnectionThread(int port) { ServerBootstrap server = new ServerBootstrap(); server.group(group);// ww w. j a v a 2 s . co m server.channel(NioServerSocketChannel.class); server.option(ChannelOption.SO_BACKLOG, 128); server.childOption(ChannelOption.SO_KEEPALIVE, true); server.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { if (blocked.containsKey(((InetSocketAddress) ch.remoteAddress()).getAddress())) { LOG.info(ch + "Rejected at socket level"); ch.close(); return; } ch.pipeline().addLast(new LengthFieldPrepender(4)); ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); ch.pipeline().addLast(new PacketEncoder()); ch.pipeline().addLast(new PacketDecoder()); ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); ch.pipeline().addLast(new ServerBootstrapConnector(addr, incomingListener)); clientsIn.add(ch); ch.closeFuture().addListener(e1 -> { clientsIn.remove(ch); }); } }); ChannelFuture f = server.bind(port); f.addListener(e -> { this.servers.add((ServerChannel) f.channel()); f.channel().closeFuture().addListener(e1 -> { this.servers.remove((ServerChannel) f.channel()); }); }); }
From source file:me.ferrybig.p2pnetwork.Peer.java
public ChannelFuture startIncomingConnectionThread(int port) { ServerBootstrap server = new ServerBootstrap(); server.group(group);//from ww w .java 2 s. co m server.channel(NioServerSocketChannel.class); server.option(ChannelOption.SO_BACKLOG, 128); server.childOption(ChannelOption.SO_KEEPALIVE, true); server.childHandler(new ChannelConstructor(incomingListener, clientsIn)); ChannelFuture f = server.bind(port); return f.addListener(e -> { if (e.isSuccess()) { this.servers.add((ServerChannel) f.channel()); f.channel().closeFuture().addListener(e1 -> { this.servers.remove((ServerChannel) f.channel()); }); } }); }
From source file:net.hasor.rsf.rpc.net.Connector.java
License:Apache License
/** * ??/* ww w.j a va 2 s. c o m*/ * @param listenLoopGroup ? */ public void startListener(NioEventLoopGroup listenLoopGroup) { // ServerBootstrap boot = new ServerBootstrap(); boot.group(listenLoopGroup, this.workLoopGroup); boot.channel(NioServerSocketChannel.class); boot.childHandler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ChannelHandler[] handlerArrays = channelHandler(); ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>(); handlers.addAll(Arrays.asList(handlerArrays)); // ?? handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF // ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()])); } }); boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); boot.childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = configBoot(boot).bind(this.bindAddress.toSocketAddress()); // final BasicFuture<RsfChannel> result = new BasicFuture<RsfChannel>(); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { future.channel().close(); result.failed(future.cause()); } else { Channel channel = future.channel(); result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Listener)); } } }); try { this.localListener = result.get(); logger.info("rsf Server started at {}", this.bindAddress); } catch (Exception e) { logger.error("rsf start listener error: " + e.getMessage(), e); throw new RsfException(ProtocolStatus.NetworkError, this.bindAddress.toString() + " -> " + e.getMessage()); } // }
From source file:net.kuujo.copycat.netty.NettyTcpProtocolServer.java
License:Apache License
@Override public synchronized CompletableFuture<Void> listen() { final CompletableFuture<Void> future = new CompletableFuture<>(); final SslContext sslContext; if (protocol.isSsl()) { try {//from w w w . j a v a2 s .c o m SelfSignedCertificate ssc = new SelfSignedCertificate(); sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (SSLException | CertificateException e) { future.completeExceptionally(e); return future; } } else { sslContext = null; } serverGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(protocol.getThreads()); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(channel.alloc())); } pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); pipeline.addLast("bytesDecoder", new ByteArrayDecoder()); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("bytesEncoder", new ByteArrayEncoder()); pipeline.addLast("handler", new ServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 128); if (protocol.getSendBufferSize() > -1) { bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize()); } if (protocol.getReceiveBufferSize() > -1) { bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize()); } bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog()); if (protocol.getTrafficClass() > -1) { bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass()); } bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // Bind and start to accept incoming connections. bootstrap.bind(host, port).addListener((ChannelFutureListener) channelFuture -> { channelFuture.channel().closeFuture().addListener(closeFuture -> { workerGroup.shutdownGracefully(); }); if (channelFuture.isSuccess()) { channel = channelFuture.channel(); future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } }); return future; }
From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java
License:Apache License
@Override public CompletableFuture<Void> start() { final CompletableFuture<Void> future = new CompletableFuture<>(); // TODO: Configure proper SSL trust store. final SslContext sslContext; if (protocol.isSsl()) { try {//from www. j a va2 s.c om SelfSignedCertificate ssc = new SelfSignedCertificate(); sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (SSLException | CertificateException e) { future.completeExceptionally(e); return future; } } else { sslContext = null; } final EventLoopGroup serverGroup = new NioEventLoopGroup(); final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads()); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(channel.alloc())); } pipeline.addLast(new ObjectEncoder(), new ObjectDecoder( ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())), new TcpProtocolServerHandler(TcpProtocolServer.this)); } }).option(ChannelOption.SO_BACKLOG, 128); if (protocol.getSendBufferSize() > -1) { bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize()); } if (protocol.getReceiveBufferSize() > -1) { bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize()); } bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay()); bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress()); bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive()); bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog()); if (protocol.getTrafficClass() > -1) { bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass()); } bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // Bind and start to accept incoming connections. bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { workerGroup.shutdownGracefully(); } }); if (channelFuture.isSuccess()) { channel = channelFuture.channel(); future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } } }); return future; }
From source file:net.mcsproject.master.network.DaemonServer.java
License:Open Source License
public DaemonServer(int port) { this.thread = new Thread(() -> { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from ww w . j av a 2s . co m ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new PacketDecoder()).addLast(new PacketEncoder()) .addLast(new PacketMessageHandler()); } }); bootstrap.option(ChannelOption.SO_BACKLOG, 50); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.bind(port).sync(); log.info("Server started!"); future.channel().closeFuture().sync(); } catch (Exception ex) { ex.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }); thread.setName("DaemonServer Thread"); thread.start(); }
From source file:net.pms.network.HTTPServer.java
License:Open Source License
public boolean start() throws IOException { hostname = configuration.getServerHostname(); InetSocketAddress address;//w ww. j a v a2s . com if (StringUtils.isNotBlank(hostname)) { LOGGER.info("Using forced address " + hostname); InetAddress tempIA = InetAddress.getByName(hostname); if (tempIA != null && networkInterface != null && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) { address = new InetSocketAddress(tempIA, port); } else { address = new InetSocketAddress(hostname, port); } } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface LOGGER.info("Using address {} found on network interface: {}", iafinal, networkInterface.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { LOGGER.info("Using localhost address"); address = new InetSocketAddress(port); } LOGGER.info("Created socket: " + address); if (configuration.isHTTPEngineV2()) { // HTTP Engine V2 bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.SO_SNDBUF, 65536).childOption(ChannelOption.SO_RCVBUF, 65536); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(address) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("HttpHandler", new HttpServerCodec()) // eliminate the need to decode http chunks from the client .addLast("aggregator", new HttpObjectAggregator(64 * 1024)) .addLast("chunkedWriter", new ChunkedWriteHandler()) .addLast("handler", new RequestHandlerV2()); } }); try { channel = bootstrap.bind().channel(); } catch (Exception e) { LOGGER.error("Another program is using port " + port + ", which UMS needs."); LOGGER.error("You can change the port UMS uses on the General Configuration tab."); LOGGER.trace("The error was: " + e); PMS.get().getFrame().setStatusCode(0, Messages.getString("PMS.141"), "icon-status-warning.png"); } if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } } else { // HTTP Engine V1 serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } runnable = new Thread(this, "HTTP Server"); runnable.setDaemon(false); runnable.start(); } return true; }
From source file:net.qing.sms.simulator.NettySmsSimulatorServer.java
License:Apache License
protected void applyConnectionOptions(ServerBootstrap bootstrap) { SocketConfig config = configuration.getSocketConfig(); bootstrap.childOption(ChannelOption.TCP_NODELAY, config.isTcpNoDelay()); if (config.getTcpSendBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize()); }// w w w. ja v a 2 s . c om if (config.getTcpReceiveBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, config.getTcpReceiveBufferSize()); } // bootstrap.option(ChannelOption.ALLOCATOR, // PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // bootstrap.childOption(ChannelOption.ALLOCATOR, // PooledByteBufAllocator.DEFAULT); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()); bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger()); bootstrap.option(ChannelOption.SO_REUSEADDR, config.isReuseAddress()); bootstrap.option(ChannelOption.SO_BACKLOG, config.getAcceptBackLog()); }