List of usage examples for io.netty.bootstrap ServerBootstrap ServerBootstrap
public ServerBootstrap()
From source file:com.vexsoftware.votifier.Votifier.java
License:Open Source License
@Mod.EventHandler public void onInit(FMLInitializationEvent event) throws IOException { // Handle configuration. if (!getDataFolder().exists()) { getDataFolder().mkdir();//from ww w. j a v a 2 s .com } File config = new File(getDataFolder() + "/config.yml"); ConfigurationLoader loader = YAMLConfigurationLoader.builder().setFile(config).build(); ConfigurationNode cfg = loader.load(); File rsaDirectory = new File(getDataFolder() + "/rsa"); /* * Use IP address from server.properties as a default for * configurations. Do not use InetAddress.getLocalHost() as it most * likely will return the main server address instead of the address * assigned to the server. */ String hostAddr = MinecraftServer.getServer().getHostname(); if (hostAddr == null || hostAddr.length() == 0) hostAddr = "0.0.0.0"; /* * Create configuration file if it does not exists; otherwise, load it */ if (!config.exists()) { try { // First time run - do some initialization. LOG.info("Configuring Votifier for the first time..."); // Initialize the configuration file. config.createNewFile(); cfg.getNode("host").setValue(hostAddr); cfg.getNode("port").setValue(8192); cfg.getNode("debug").setValue(false); /* * Remind hosted server admins to be sure they have the right * port number. */ LOG.info("------------------------------------------------------------------------------"); LOG.info("Assigning Votifier to listen on port 8192. If you are hosting Forge on a"); LOG.info("shared server please check with your hosting provider to verify that this port"); LOG.info("is available for your use. Chances are that your hosting provider will assign"); LOG.info("a different port, which you need to specify in config.yml"); LOG.info("------------------------------------------------------------------------------"); String token = TokenUtil.newToken(); ConfigurationNode tokenSection = cfg.getNode("tokens"); tokenSection.getNode("default").setValue(token); LOG.info("Your default Votifier token is " + token + "."); LOG.info("You will need to provide this token when you submit your server to a voting"); LOG.info("list."); LOG.info("------------------------------------------------------------------------------"); loader.save(cfg); } catch (Exception ex) { LOG.log(Level.FATAL, "Error creating configuration file", ex); gracefulExit(); return; } } else { // Load configuration. cfg = loader.load(); } /* * Create RSA directory and keys if it does not exist; otherwise, read * keys. */ try { if (!rsaDirectory.exists()) { rsaDirectory.mkdir(); keyPair = RSAKeygen.generate(2048); RSAIO.save(rsaDirectory, keyPair); } else { keyPair = RSAIO.load(rsaDirectory); } } catch (Exception ex) { LOG.fatal("Error reading configuration file or RSA tokens", ex); gracefulExit(); return; } // Load Votifier tokens. ConfigurationNode tokenSection = cfg.getNode("tokens"); if (tokenSection != null) { Map<Object, ? extends ConfigurationNode> websites = tokenSection.getChildrenMap(); for (Map.Entry<Object, ? extends ConfigurationNode> website : websites.entrySet()) { tokens.put((String) website.getKey(), KeyCreator.createKeyFrom(website.getValue().getString())); LOG.info("Loaded token for website: " + website.getKey()); } } else { LOG.warn("No websites are listed in your configuration."); } // Initialize the receiver. String host = cfg.getNode("host").getString(hostAddr); int port = cfg.getNode("port").getInt(8192); debug = cfg.getNode("debug").getBoolean(false); if (debug) LOG.info("DEBUG mode enabled!"); serverGroup = new NioEventLoopGroup(1); new ServerBootstrap().channel(NioServerSocketChannel.class).group(serverGroup) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel channel) throws Exception { channel.attr(VotifierSession.KEY).set(new VotifierSession()); channel.pipeline().addLast("greetingHandler", new VotifierGreetingHandler()); channel.pipeline().addLast("protocolDifferentiator", new VotifierProtocolDifferentiator()); channel.pipeline().addLast("voteHandler", new VoteInboundHandler()); } }).bind(host, port).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { serverChannel = future.channel(); LOG.info("Votifier enabled."); } else { LOG.fatal("Votifier was not able to bind to " + future.channel().localAddress(), future.cause()); } } }); }
From source file:com.vip.netty.basic.TimeServer.java
License:Apache License
public void bind(int port) throws Exception { // ??NIO/*w w w. jav a 2s. co m*/ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler()); // ??? ChannelFuture f = b.bind(port).sync(); // ??? f.channel().closeFuture().sync(); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.vip.netty.protocol.file.FileServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w ww. j ava 2 s .c om*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() { /* * (non-Javadoc) * * @see * io.netty.channel.ChannelInitializer#initChannel(io * .netty.channel.Channel) */ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8), new FileServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); System.out.println("Start file server at port : " + port); f.channel().closeFuture().sync(); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.vip.netty.protocol.http.fileServer.HttpFileServer.java
License:Apache License
public void run(final int port, final String url) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// www . j a va2 s . c om ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url)); } }); ChannelFuture future = b.bind("192.168.0.106", port).sync(); System.out.println( "HTTP??? : " + "http://192.168.0.106:" + port + url); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.vmware.dcp.common.http.netty.NettyHttpListener.java
License:Open Source License
public void start(int port, String bindAddress) throws Throwable { ExecutorServiceFactory f = (tc) -> { return Executors.newFixedThreadPool(EVENT_LOOP_THREAD_COUNT, r -> new Thread(r, this.host.getUri().toString() + "/netty-listener/" + this.host.getId())); };/*from w w w. ja v a 2 s .c o m*/ this.parentGroup = new NioEventLoopGroup(EVENT_LOOP_THREAD_COUNT, f); this.childGroup = new NioEventLoopGroup(EVENT_LOOP_THREAD_COUNT, f); if (this.childChannelHandler == null) { this.childChannelHandler = new NettyHttpServerInitializer(this.host, this.sslContext); } ServerBootstrap b = new ServerBootstrap(); b.group(this.parentGroup, this.childGroup).channel(NioServerSocketChannel.class) .childHandler(this.childChannelHandler); InetSocketAddress addr = null; if (bindAddress != null) { addr = new InetSocketAddress(bindAddress, port); } else { this.host.log(Level.WARNING, "*** Binding to all interfaces, please supply a bindAddress instead ***"); addr = new InetSocketAddress(port); } this.serverChannel = b.bind(addr).sync().channel(); this.serverChannel.config().setOption(ChannelOption.SO_LINGER, 0); this.port = ((InetSocketAddress) this.serverChannel.localAddress()).getPort(); }
From source file:com.vmware.xenon.common.http.netty.NettyHttpListener.java
License:Open Source License
@Override public void start(int port, String bindAddress) throws Throwable { this.nettyExecutorService = Executors.newFixedThreadPool(EVENT_LOOP_THREAD_COUNT, r -> new Thread(r, this.host.getUri().toString() + "/netty-listener/" + this.host.getId())); this.eventLoopGroup = new NioEventLoopGroup(EVENT_LOOP_THREAD_COUNT, this.nettyExecutorService); if (this.childChannelHandler == null) { this.childChannelHandler = new NettyHttpServerInitializer(this.host, this.sslContext, this.responsePayloadSizeLimit); }// ww w . java2 s . c o m ServerBootstrap b = new ServerBootstrap(); b.group(this.eventLoopGroup).channel(NioServerSocketChannel.class).childHandler(this.childChannelHandler); InetSocketAddress addr; if (bindAddress != null) { addr = new InetSocketAddress(bindAddress, port); } else { this.host.log(Level.WARNING, "*** Binding to all interfaces, please supply a bindAddress instead ***"); addr = new InetSocketAddress(port); } this.serverChannel = b.bind(addr).sync().channel(); this.serverChannel.config().setOption(ChannelOption.SO_LINGER, 0); this.port = ((InetSocketAddress) this.serverChannel.localAddress()).getPort(); this.isListening = true; }
From source file:com.weibo.api.motan.transport.netty.NettyServer.java
License:Apache License
private synchronized void initServerBootstrap() { boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue()); final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue()); int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(), URLParamType.maxServerConnection.getIntValue()); int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), URLParamType.workerQueueSize.getIntValue()); int minWorkerThread = 0, maxWorkerThread = 0; if (shareChannel) { minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER); } else {//from w w w. j a v a 2 s . c o m minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER); } standardThreadExecutor = (standardThreadExecutor != null && !standardThreadExecutor.isShutdown()) ? standardThreadExecutor : new StandardThreadExecutor(minWorkerThread, maxWorkerThread, workerQueueSize, new DefaultThreadFactory("NettyServer-" + url.getServerPortStr(), true)); standardThreadExecutor.prestartAllCoreThreads(); // ?? channelManage = new NettyServerChannelManage(maxServerConnection); final NettyChannelHandler handler = new NettyChannelHandler(NettyServer.this, messageHandler, standardThreadExecutor); EventLoopGroup bossGroup = new NioEventLoopGroup(1, new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, String.format("NettyBoss_%d", this.threadIndex.incrementAndGet())); } }); EventLoopGroup workerGroup = new NioEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(channelManage); ch.pipeline().addLast(new NettyEncoder(codec, NettyServer.this)); ch.pipeline().addLast(new NettyDecoder(codec, NettyServer.this, maxContentLength)); ch.pipeline().addLast(handler); } }); }
From source file:com.weibo.api.motan.transport.netty4.http.Netty4HttpServer.java
License:Apache License
@Override public boolean open() { if (isAvailable()) { return true; }//from w w w . j a v a 2 s .c o m if (channel != null) { channel.close(); } if (bossGroup == null) { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); } boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue()); // TODO max connection protect int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(), URLParamType.maxServerConnection.getIntValue()); int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), 500); int minWorkerThread = 0, maxWorkerThread = 0; if (shareChannel) { minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER); } else { minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER); } final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue()); final NettyHttpRequestHandler handler = new NettyHttpRequestHandler(this, messageHandler, new ThreadPoolExecutor(minWorkerThread, maxWorkerThread, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(workerQueueSize))); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(maxContentLength)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("serverHandler", handler); } }).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, false); ChannelFuture f; try { f = b.bind(url.getPort()).sync(); channel = f.channel(); } catch (InterruptedException e) { LoggerUtil.error("init http server fail.", e); return false; } state = ChannelState.ALIVE; StatsUtil.registryStatisticCallback(this); LoggerUtil.info("Netty4HttpServer ServerChannel finish Open: url=" + url); return true; }
From source file:com.weibo.yar.yarserver.NettyYarServer.java
License:Apache License
public void start(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from ww w .ja va2 s .c om ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("serverHandler", new HttpServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.whizzosoftware.hobson.hub.websockets.WebSocketsPlugin.java
License:Open Source License
@Override public void onStartup(PropertyContainer config) { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer(clientChannels, getAccessManager())); b.bind(PORT).addListener(new GenericFutureListener<ChannelFuture>() { @Override/*from w ww . ja va2 s .c o m*/ public void operationComplete(ChannelFuture future) throws Exception { WebSocketsPlugin.this.channel = future.channel(); logger.debug("WebSocket server started at port {}", PORT); getHubManager().getLocalManager().setWebSocketInfo("ws", PORT, null); } }); }