List of usage examples for io.netty.bootstrap ServerBootstrap ServerBootstrap
public ServerBootstrap()
From source file:com.friz.owari.network.server.Server.java
License:Open Source License
@Override public void initialize() throws NoSuchAlgorithmException { bootstrap = new ServerBootstrap(); bootstrap.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override/* www. ja v a 2 s . c o m*/ protected void initChannel(NioSocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(HandshakeDecoder.class.getName(), new HandshakeDecoder()); pipeline.addLast(HandshakeEncoder.class.getName(), new HandshakeEncoder()); pipeline.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0)); pipeline.addLast(ServerChannelHandler.class.getName(), new ServerChannelHandler(Server.this)); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true); hub.listen(HandshakeEvent.class, new HandshakeListener()); hub.listen(ExchangeRecieveEvent.class, new ExchangeListener()); final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DH"); keyPairGenerator.initialize(1024); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); privateKey = keyPair.getPrivate(); publicKey = keyPair.getPublic(); }
From source file:com.friz.update.UpdateServer.java
License:Open Source License
@Override public void initialize() { group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()); bootstrap = new ServerBootstrap(); UpdateServer s = this; bootstrap.group(group).channel(NioServerSocketChannel.class) //.handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override//from ww w . j a v a2 s .c o m protected void initChannel(NioSocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(UpdateInitEncoder.class.getName(), new UpdateInitEncoder()); p.addLast(UpdateInitDecoder.class.getName(), new UpdateInitDecoder()); p.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0)); p.addLast(UpdateChannelHandler.class.getName(), new UpdateChannelHandler(s)); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true); hub.listen(UpdateRequestEvent.class, new UpdateRequestEventListener()); hub.listen(XorRequestEvent.class, new XorRequestEventListener()); hub.listen(FileRequestEvent.class, new FileRequestEventListener()); service.startAsync(); }
From source file:com.fruit.core.socket.SocketServer.java
License:Apache License
public SocketServer(int port, ChannelHandler channelHander) { ServerBootstrap b = new ServerBootstrap(); try {//from www . j ava2 s. co m b.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class) .childHandler(new FruitServerPipelineFactory()); b.bind(port).sync().channel().closeFuture().sync(); } catch (Exception e) { logger.error("SocketServer", e); } finally { b.shutdown(); } }
From source file:com.fsocks.SocksServer.java
License:Apache License
public static void main(String[] args) throws Exception { Properties properties = new Properties(); try {/*from ww w .ja va 2 s .com*/ properties.load(SocksServer.class.getResourceAsStream("/config.properties")); PORT = Integer.parseInt(properties.getProperty("port")); } catch (Exception e) { logger.warn("load config.properties error, default port 11080, auth false!"); } EventLoopGroup bossGroup = new NioEventLoopGroup(16); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { 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(); } catch (Exception e) { logger.error("SocksServer server error,", e); } finally { logger.error("SocksServer is shutdown"); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.galaxy.netty.http.HttpStaticFileServer.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 a v a 2 s. c o m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpStaticFileServerInitializer()); 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 { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.gdut.Netty_testing.dongjun.server.ElectricControlServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from w w w .ja v a 2 s . c o m*/ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ElectricControlServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java
License:Apache License
/** * /* w ww .ja v a2 s .c o m*/ * @Title: main * @Description: TODO * @param @param args * @param @throws Exception * @return void * @throws */ public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } 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), new TimeEncoder(), new TimeServerHandler()); // new TimeEncoder(), } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); f.addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { // TODO Auto-generated method stub System.out.println("success " + future.isSuccess()); } }); // 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:com.gemstone.gemfire.redis.GemFireRedisServer.java
License:Apache License
/** * Helper method to start the server listening for connections. The * server is bound to the port specified by {@link GemFireRedisServer#serverPort} * /*from w w w . j a v a2 s .c o m*/ * @throws IOException * @throws InterruptedException */ private void startRedisServer() throws IOException, InterruptedException { ThreadFactory selectorThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-SelectorThread-" + counter.incrementAndGet()); t.setDaemon(true); return t; } }; ThreadFactory workerThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-WorkerThread-" + counter.incrementAndGet()); return t; } }; bossGroup = null; workerGroup = null; Class<? extends ServerChannel> socketClass = null; if (singleThreadPerConnection) { bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory); workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory); socketClass = OioServerSocketChannel.class; } else { bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory); workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory); socketClass = NioServerSocketChannel.class; } InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem(); String pwd = system.getConfig().getRedisPassword(); final byte[] pwdB = Coder.stringToBytes(pwd); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (logger.fineEnabled()) logger.fine("GemFireRedisServer-Connection established with " + ch.remoteAddress()); ChannelPipeline p = ch.pipeline(); p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder()); p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GemFireRedisServer.this, pwdB)); } }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GemFireRedisServer.connectTimeoutMillis) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync(); if (this.logger.infoEnabled()) { String logMessage = "GemFireRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads; if (this.singleThreadPerConnection) logMessage += ", One worker thread per connection"; else logMessage += ", Worker threads: " + this.numWorkerThreads; this.logger.info(logMessage); } this.serverChannel = f.channel(); }
From source file:com.github.ambry.rest.NettyServer.java
License:Open Source License
@Override public void start() throws InstantiationException { long startupBeginTime = System.currentTimeMillis(); try {/*from w w w . j a va 2 s . c o m*/ logger.trace("Starting NettyServer deployment"); ServerBootstrap b = new ServerBootstrap(); // Netty creates a new instance of every class in the pipeline for every connection // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, nettyConfig.nettyServerSoBacklog) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(channelInitializer); b.bind(nettyConfig.nettyServerPort).sync(); logger.info("NettyServer now listening on port {}", nettyConfig.nettyServerPort); } catch (InterruptedException e) { logger.error("NettyServer start await was interrupted", e); nettyMetrics.nettyServerStartError.inc(); throw new InstantiationException( "Netty server bind to port [" + nettyConfig.nettyServerPort + "] was interrupted"); } finally { long startupTime = System.currentTimeMillis() - startupBeginTime; logger.info("NettyServer start took {} ms", startupTime); nettyMetrics.nettyServerStartTimeInMs.update(startupTime); } }
From source file:com.github.brandtg.switchboard.LogReceiver.java
License:Apache License
/** * A server that listens for log regions and pipes them to an output stream. * * @param address/* w w w.ja va 2s . com*/ * The socket address on which to listen * @param eventExecutors * The Netty executor service to use for incoming traffic * @param outputStream * The output stream to which all data should be piped */ public LogReceiver(InetSocketAddress address, EventLoopGroup eventExecutors, final OutputStream outputStream) { this.address = address; this.isShutdown = new AtomicBoolean(true); this.listeners = new HashSet<Object>(); this.serverBootstrap = new ServerBootstrap().group(eventExecutors).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)); ch.pipeline().addLast(new LogMessageHandler(outputStream, listeners)); } }); }