List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.jjzhk.Chapter13.file.FileServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* w w w. jav a 2s. c o m*/ 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.jjzhk.Chapter14.netty.NettyClient.java
License:Apache License
public void connect(int port, String host) throws Exception { try {/*from w ww .j a v a 2 s . c o 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(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler()); } }); ChannelFuture future = b.connect(new InetSocketAddress(host, port), new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync(); future.channel().closeFuture().sync(); } finally { executor.execute(new Runnable() { public void run() { try { TimeUnit.SECONDS.sleep(1); try { connect(NettyConstant.PORT, NettyConstant.REMOTEIP); } catch (Exception e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); } }
From source file:com.JohnnyTests.NettySimpleChat.gui.NettyTCPClient.java
License:Apache License
public void startClient() throws Exception { // Log//from w w w . j a v a2 s . com Logger logger = Logger.getLogger(NettyTCPClient.class); group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("encoder", new StringEncoder()); ch.pipeline().addLast("decoder", new StringDecoder()); // and then business logic. if (handler != null) ch.pipeline().addLast("handler", handler); } }); ChannelFuture f = bootstrap.connect(host, port).sync(); ch = f.channel(); System.out.println("Connected!"); }
From source file:com.jt.flash.proxy.handler.ProxyFrontendHandler.java
License:Apache License
private void processRequest(final ChannelHandlerContext ctx, final Object msg, final Channel inboundChannel, String host, final int port) { Bootstrap b = buildBackendBootstrap(ctx, inboundChannel, port); ChannelFuture f = b.connect(host, port); outboundChannel = f.channel(); f.addListener(new ChannelFutureListener() { @Override/*from ww w. j a v a 2 s .co m*/ public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { log.info("connect ok, write {}", msg); outboundChannel.writeAndFlush(msg); /* .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { ctx.channel().read(); } else { future.channel().close(); } } });*/ } else { log.warn("connect fail"); inboundChannel.close(); } } }); }
From source file:com.khs.microservice.whirlpool.whirlpoolserver.WhirlpoolServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w .j ava 2 s.co m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("handler", new WhirlpoolServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); logger.info("Whirlpool Server started"); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { logger.info("Whirlpool Server shutdown started"); // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); logger.info("Whirlpool Server shutdown completed"); } }
From source file:com.khs.stockticker.StockTickerServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w.j ava 2 s . com*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("handler", new StockTickerServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); logger.info("Ticket Symbol Server started"); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { logger.info("Ticket Symbol Server shutdown started"); // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); logger.info("Ticket Symbol Server shutdown completed"); } }
From source file:com.king.platform.net.http.netty.ChannelManager.java
License:Apache License
private void sendOnNewChannel(final HttpRequestContext httpRequestContext, final RequestEventBus requestEventBus) { final ServerInfo serverInfo = httpRequestContext.getServerInfo(); ChannelFuture channelFuture = connect(serverInfo); channelFuture.addListener(new ChannelFutureListener() { @Override//from w w w. j a v a 2 s . c o m public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { requestEventBus.triggerEvent(Event.CREATED_CONNECTION, serverInfo); requestEventBus.triggerEvent(Event.onConnected); Channel channel = future.channel(); channel.attr(ServerInfo.ATTRIBUTE_KEY).set(serverInfo); logger.trace("Opened a new channel {}, for request {}", channel, httpRequestContext); sendOnChannel(channel, httpRequestContext, requestEventBus); } else { logger.trace("Failed to opened a new channel for request {}", httpRequestContext); Throwable cause = future.cause(); requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, cause); } } }); }
From source file:com.kingmed.dp.lisclient.demo.DiscardServer.java
public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// www . j ava 2 s. com 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(new DiscardServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.lambdaworks.redis.AbstractRedisClient.java
License:Apache License
/** * Connect and initialize a channel from {@link ConnectionBuilder}. * * @param connectionBuilder must not be {@literal null}. * @return the {@link ConnectionFuture} to synchronize the connection process. * @since 4.4//from w ww .j a v a2s. c o m */ @SuppressWarnings("unchecked") protected <K, V, T extends RedisChannelHandler<K, V>> ConnectionFuture<T> initializeChannelAsync( ConnectionBuilder connectionBuilder) { SocketAddress redisAddress = connectionBuilder.socketAddress(); if (clientResources.eventExecutorGroup().isShuttingDown()) { throw new IllegalStateException("Cannot connect, Event executor group is terminated."); } logger.debug("Connecting to Redis at {}", redisAddress); CompletableFuture<Channel> channelReadyFuture = new CompletableFuture<>(); Bootstrap redisBootstrap = connectionBuilder.bootstrap(); RedisChannelInitializer initializer = connectionBuilder.build(); redisBootstrap.handler(initializer); ChannelFuture connectFuture = redisBootstrap.connect(redisAddress); connectFuture.addListener(future -> { if (!future.isSuccess()) { logger.debug("Connecting to Redis at {}: {}", redisAddress, future.cause()); connectionBuilder.commandHandler().initialState(); channelReadyFuture.completeExceptionally(future.cause()); return; } CompletableFuture<Boolean> initFuture = (CompletableFuture<Boolean>) initializer.channelInitialized(); initFuture.whenComplete((success, throwable) -> { if (throwable == null) { logger.debug("Connecting to Redis at {}: Success", redisAddress); RedisChannelHandler<?, ?> connection = connectionBuilder.connection(); connection.registerCloseables(closeableResources, connection); channelReadyFuture.complete(connectFuture.channel()); return; } logger.debug("Connecting to Redis at {}, initialization: {}", redisAddress, throwable); connectionBuilder.commandHandler().initialState(); Throwable failure; if (throwable instanceof RedisConnectionException) { failure = throwable; } else if (throwable instanceof TimeoutException) { failure = new RedisConnectionException("Could not initialize channel within " + connectionBuilder.getTimeout() + " " + connectionBuilder.getTimeUnit(), throwable); } else { failure = throwable; } channelReadyFuture.completeExceptionally(failure); CompletableFuture<Boolean> response = new CompletableFuture<>(); response.completeExceptionally(failure); }); }); return new DefaultConnectionFuture<>(redisAddress, channelReadyFuture.thenApply(channel -> (T) connectionBuilder.connection())); }
From source file:com.lambdaworks.redis.protocol.ReconnectionHandler.java
License:Apache License
protected boolean reconnect(InternalLogLevel infoLevel) throws Exception { SocketAddress remoteAddress = socketAddressSupplier.get(); try {//from w w w.jav a2s .c o m long timeLeft = timeoutUnit.toNanos(timeout); long start = System.nanoTime(); logger.debug("Reconnecting to Redis at {}", remoteAddress); ChannelFuture currentFuture = this.currentFuture = bootstrap.connect(remoteAddress); if (!currentFuture.await(timeLeft, TimeUnit.NANOSECONDS)) { if (currentFuture.isCancellable()) { currentFuture.cancel(true); } throw new TimeoutException( "Reconnection attempt exceeded timeout of " + timeout + " " + timeoutUnit); } currentFuture.sync(); Channel channel = currentFuture.channel(); RedisChannelInitializer channelInitializer = channel.pipeline().get(RedisChannelInitializer.class); CommandHandler<?, ?> commandHandler = channel.pipeline().get(CommandHandler.class); if (channelInitializer == null) { logger.warn("Reconnection attempt without a RedisChannelInitializer in the channel pipeline"); close(channel); return false; } if (commandHandler == null) { logger.warn("Reconnection attempt without a CommandHandler in the channel pipeline"); close(channel); return false; } try { timeLeft -= System.nanoTime() - start; channelInitializer.channelInitialized().get(Math.max(0, timeLeft), TimeUnit.NANOSECONDS); if (logger.isDebugEnabled()) { logger.log(infoLevel, "Reconnected to {}, Channel {}", remoteAddress, ChannelLogDescriptor.logDescriptor(channel)); } else { logger.log(infoLevel, "Reconnected to {}", remoteAddress); } return true; } catch (TimeoutException e) { channelInitializer.channelInitialized().cancel(true); } catch (Exception e) { if (clientOptions.isCancelCommandsOnReconnectFailure()) { commandHandler.reset(); } if (clientOptions.isSuspendReconnectOnProtocolFailure()) { logger.error("Cannot initialize channel. Disabling autoReconnect", e); setReconnectSuspended(true); } else { logger.error("Cannot initialize channel.", e); throw e; } } } finally { this.currentFuture = null; } return false; }