List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvous.MsgEchoPeerBase.java
License:Apache License
public void run() throws Exception { // Configure the peer. final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous"); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER); try {/*from www . j av a 2s.co m*/ final Bootstrap boot = new Bootstrap(); boot.group(connectGroup).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS) .handler(new ChannelInitializer<UdtChannel>() { @Override public void initChannel(final UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoPeerHandler(messageSize)); } }); // Start the peer. final ChannelFuture f = boot.connect(peer, self).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. connectGroup.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvousBytes.ByteEchoPeerBase.java
License:Apache License
public void run() throws Exception { final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous"); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER); try {//ww w . ja va 2s . co m final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(connectGroup).channelFactory(NioUdtProvider.BYTE_RENDEZVOUS) .handler(new ChannelInitializer<UdtChannel>() { @Override protected void initChannel(UdtChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoPeerHandler(messageSize)); } }); final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync(); future.channel().closeFuture().sync(); } finally { connectGroup.shutdownGracefully(); } }
From source file:com.foilen.smalltools.net.netty.NettyServer.java
License:Open Source License
/** * Start the server./*ww w. j a va2s . c o m*/ * * @param port * the port to listen on (0 for a random port ; get it with {@link #getPort()}) * @param trustedCertificates * (optional) the certificate to trust connections from * @param certificate * (optional) the server's certificate * @param channelHandlerContainers * the channel handlers for the incoming connections */ public void start(final int port, final RSATrustedCertificates trustedCertificates, final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) { AssertTools.assertNull(thread, "Server is already started"); final CountDownLatch countDownLatch = new CountDownLatch(1); thread = new Thread(() -> { try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { InetSocketAddress remoteAddress = socketChannel.remoteAddress(); logger.info("Got a connection from {}:{}", remoteAddress.getHostName(), remoteAddress.getPort()); // Add sslCtx if needed if (trustedCertificates != null || certificate != null) { TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null : RSATools.createTrustManagerFactory(trustedCertificates); KeyManagerFactory keyManagerFactory = certificate == null ? null : RSATools.createKeyManagerFactory(certificate); CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE; SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null, trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter, null, 0, 0); SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc()); if (trustManagerFactory == null) { logger.debug("Will not verify client's identity"); } else { logger.debug("Will verify client's identity"); SSLEngine sslEngine = sslHandler.engine(); sslEngine.setNeedClientAuth(true); } socketChannel.pipeline().addLast(sslHandler); } // Add the channel handlers for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) { socketChannel.pipeline() .addLast(ReflectionTools.instantiate( channelHandlerContainer.getChannelHandlerClass(), channelHandlerContainer.getConstructorParams())); } } }) // .option(ChannelOption.SO_BACKLOG, 128) // .childOption(ChannelOption.SO_KEEPALIVE, true); bindedPort = port; logger.info("Server on port {} is starting...", port); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); SocketAddress socketAddress = channelFuture.channel().localAddress(); if (socketAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress; bindedPort = inetSocketAddress.getPort(); } logger.info("Server on port {} is started", bindedPort); countDownLatch.countDown(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { logger.info("Server on port {} is interrupted", bindedPort); } finally { countDownLatch.countDown(); } logger.info("Server on port {} is stopped", bindedPort); }); thread.setName("Netty Server-" + bindedPort); thread.start(); try { countDownLatch.await(); } catch (InterruptedException e) { logger.error("Interrupted while waiting for the server to start"); } }
From source file:com.frank.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 {/*from w w w . j a v a 2s . co m*/ 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.1.102", port).sync(); System.out.println( "HTTP??? : " + "http://192.168.1.102:" + port + url); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.friz.update.network.UpdateSessionContext.java
License:Open Source License
public void writeSuccess(int status) { channel.writeAndFlush(new UpdateResponseEvent(status)).addListener(new ChannelFutureListener() { @Override/*from w ww . jav a2s .c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ChannelPipeline p = future.channel().pipeline(); p.remove(UpdateInitDecoder.class); p.remove(UpdateInitEncoder.class); p.addFirst(XorEncoder.class.getName(), new XorEncoder()); p.addFirst(UpdateEncoder.class.getName(), new UpdateEncoder()); p.addFirst(UpdateDecoder.class.getName(), new UpdateDecoder()); handshakeComplete = true; } } }); }
From source file:com.gdut.Netty_testing.time_server.client.TimeClient.java
License:Apache License
/** * /*from w w w .java2 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.git final SslContext sslCtx; if (SSL) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler(), new TimeOutBoundHandler(), new LoggingHandler(LogLevel.INFO)); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT).sync(); // channel.connect(remoteAddress, promise); // ?connect()??OutboundHandler // ?InboundHandlerlogic??? // ?? // InboundHandler?writeAndFlush(Object // msg)??OutBoundHandler // ?? ctx.write(encoded, promise); // writeAndFlush(Object msg) // ?InboundHandler decoder? // ?TimeClientHandler()Handler, // ctx.close();?OutBoundHandler ? Thread.sleep(9000); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java
License:Apache License
/** * /*from www . ja v a 2 s. co 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 ww w . jav a 2 s . co 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.herong.rpc.netty.protobuf.demo1.ProtobufClient.java
License:Apache License
public void run() throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {//from w ww.j a v a 2 s . co m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline() // .addLast("frameDecoder", new ProtobufVarint32FrameDecoder()) // .addLast("protobufDecoder", new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance())) // .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender()) .addLast("protobufEncoder", new ProtobufEncoder()) // .addLast("handler", new ProtobufClientHandler()); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); sendMsg(f.channel()); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.github.herong.rpc.netty.protobuf.demo1.ProtobufServer.java
License:Apache License
public void run() throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// w w w . j a v a 2s . co m 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 { ch.pipeline() // .addLast("frameDecoder", new ProtobufVarint32FrameDecoder()) // .addLast("protobufDecoder", new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance())) // .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender()) .addLast("protobufEncoder", new ProtobufEncoder()) // .addLast("handler", new ProtobufServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(port).sync(); // 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(); } }