List of usage examples for io.netty.channel EventLoopGroup shutdownGracefully
Future<?> shutdownGracefully();
From source file:ccwihr.client.t2.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // // Configure SSL. // final SslContext sslCtx; // if (SSL) { // SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; // sslCtx = SslContextBuilder.forClient() // .sslProvider(provider) // /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. // * Please refer to the HTTP/2 specification for cipher requirements. */ // .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) // .trustManager(InsecureTrustManagerFactory.INSTANCE) // .applicationProtocolConfig(new ApplicationProtocolConfig( // Protocol.ALPN, // // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. // SelectorFailureBehavior.NO_ADVERTISE, // // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. // SelectedListenerFailureBehavior.ACCEPT, // ApplicationProtocolNames.HTTP_2, // ApplicationProtocolNames.HTTP_1_1)) // .build(); // } else { // sslCtx = null; // }/* w w w. j av a 2 s. co m*/ EventLoopGroup workerGroup = new NioEventLoopGroup(); // Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE); Http2ClientInitializer initializer = new Http2ClientInitializer(null, Integer.MAX_VALUE); try { // Configure the client. Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); // Wait for the HTTP/2 upgrade to occur. Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS); HttpResponseHandler responseHandler = initializer.responseHandler(); int streamId = 3; HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP; AsciiString hostName = new AsciiString(HOST + ':' + PORT); System.err.println("Sending request(s)..."); if (URL != null) { // Create a simple GET request. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } if (URL2 != null) { // Create a simple POST request with a body. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8))); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } responseHandler.awaitResponses(5, TimeUnit.SECONDS); System.out.println("Finished HTTP/2 request(s)"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); } }
From source file:chapter01.EchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {// ww w . ja v a 2s . co m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new EchoClientHandler()); } }); ChannelFuture f = b.connect("localhost", 8888).sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
From source file:chapter10.WebSocketServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// www . j a va 2 s . c o m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); pipeline.addLast("handler", new WebSocketServerHandler()); } }); Channel ch = b.bind(port).sync().channel(); System.out.println("Web socket server started at port " + port + '.'); System.out.println("Open your browser and navigate to http://localhost:" + port + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:ChatClient.ChatClient.java
public void run() { EventLoopGroup group = new NioEventLoopGroup(); try {//ww w. j a v a2 s.c o m Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class) .handler(new ChatClientInitializer()); Channel channel = bootstrap.connect(host, PORT).sync().channel(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { try { String line = in.readLine(); channel.writeAndFlush(new StringMessage(0, 0, "Client", line)); System.out.println("ECHO: " + line); } catch (IOException ex) { System.err.println("Writing error"); } } } catch (InterruptedException ex) { System.err.println("Interrupt Error"); } finally { group.shutdownGracefully(); } }
From source file:ChatServer.ChatServer.java
public void run() { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w w w. j a v a 2 s. c om ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class).childHandler(new ChatServerInitializer()); bootstrap.bind(port).channel().closeFuture().sync(); } catch (InterruptedException ex) { } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:cl.uandes.so.server.LoginServer.java
public void killServer(EventLoopGroup group) throws InterruptedException { Thread.sleep(60000); group.shutdownGracefully(); }
From source file:cl.uandes.so.server.LoginServer.java
public void run() throws Exception { final EventLoopGroup group = new NioEventLoopGroup(); // (1) try {/* ww w. jav a2 s .co m*/ Thread t1 = new Thread(new Runnable() { public void run() { System.out.println("Login Server will stop in 60 seconds..."); try { Thread.sleep(10000); } catch (InterruptedException ex) { Logger.getLogger(LoginServer.class.getName()).log(Level.SEVERE, null, ex); } group.shutdownGracefully(); } }); Thread t2 = new Thread(new Runnable() { public void run() { int counter = 1; while (counter < 10) { System.out.println("Time : " + counter); try { Thread.sleep(1000); counter++; } catch (InterruptedException e) { e.printStackTrace(); } } } }); t1.start(); t2.start(); Bootstrap b = new Bootstrap(); // (2) b.group(group).channel(NioDatagramChannel.class) // (3) .option(ChannelOption.SO_BROADCAST, true).handler(new LoginServerHandler(multicastgroup)); // Bind and start to accept incoming connections. b.bind(port).sync().channel().closeFuture().await(); // (7) } finally { group.shutdownGracefully(); } }
From source file:client.DiscardClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w w w. j a va2 s .c o m sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT)); } p.addLast(new DiscardClientHandler()); } }); // Make the connection attempt. ChannelFuture f = b.connect(HOST, PORT).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
From source file:club.jmint.crossing.server.CrossingServer.java
License:Apache License
public void start() { //load configuration //ConfigWizard cw = (ConfigWizard)WizardManager.getWizard("ConfigWizard"); ServerConfig config = (ServerConfig) ConfigWizard.getConfig(Constants.CONFIG_SERVER); this.address = config.getItem("server.bind_address"); this.port = Integer.parseInt(config.getItem("server.port")); this.backlog = Integer.parseInt(config.getItem("server.backlog")); this.ssl = Boolean.parseBoolean(config.getItem("server.ssl")); //Configure SSL if (ssl) {/*from w ww . j a v a 2 s. c om*/ try { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } catch (Exception e) { CrossLog.printStackTrace(e); } } 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, backlog).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ServerChannelInitializer(sslCtx)); // Start the server. ChannelFuture f = b.bind(port).sync(); CrossLog.logger.info("Crossing Server started......"); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } catch (InterruptedException e) { CrossLog.printStackTrace(e); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); CrossLog.logger.info("Crossing Server shutdown......"); } }
From source file:cn.ac.iscas.pebble.open.dc.nettyClient.NettyOracleClientPassRecord.java
public void operateOnTime() { TimerTask task = new TimerTask() { @Override/*from ww w .j a va 2s . com*/ public void run() { // TODO Auto-generated method stub EventLoopGroup group = new NioEventLoopGroup(); int result = 0; try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new nettyClientInitializer()); // Make a new connection. Channel ch = b.connect(host, port).sync().channel(); // Get the handler instance to initiate the request. nettyClientHandler handler = ch.pipeline().get(nettyClientHandler.class); //read mid file File file = new File(logMidFile); BufferedReader reader = null; Date dateStart = cc.getTime(); String tmpString; try { reader = new BufferedReader(new FileReader(file)); while ((tmpString = reader.readLine()) != null && tmpString.equals("") == false) { Date dateTmp = sdf.parse(tmpString); if (dateStart.compareTo(dateTmp) < 0) dateStart = dateTmp; } System.out.println("start time from log file:" + dateStart); // System.out.println("end time:"+dateEnd); } catch (IOException e) { //e.printStackTrace(); System.out.println("IO/logPassRecord.txt" + " is not exit."); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { e1.printStackTrace(); } } } //set start and end time cc.setTime(dateStart); dataStartTime = sdf.format(cc.getTime()); int min = cc.get(Calendar.MINUTE); cc.set(Calendar.MINUTE, min + intervalTime); dataEndTime = sdf.format(cc.getTime()); //clean data CleanDataRealtime cleanDataRealtime = new CleanDataRealtime(propPathClean); cleanDataRealtime.setDataStartTime(dataStartTime); cleanDataRealtime.setDataEndTime(dataEndTime); cleanDataRealtime.cleanDataRealtime(); mapCleanNetty = cleanDataRealtime.getMapClean(); if (mapCleanNetty == null) System.out.println("mapCleanNetty null"); else result = cleanAndSend(handler); // Request and get the response. // Close the connection. ch.close(); //write txt file WriteTxtRealtime writeTxtRealtime = new WriteTxtRealtime(); writeTxtRealtime.setMapCleanTxt(mapCleanNetty); writeTxtRealtime.setTxtFilePath(txtFileRootPath); writeTxtRealtime.setStrDateBegin(dataStartTime); writeTxtRealtime.WriteTxtRealtime(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { group.shutdownGracefully(); } if (result != 0) { try { throw new Exception("send data fail."); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; Timer timer = new Timer(); timer.schedule(task, cc.getTime(), intervalTime * 60 * 1000); }