List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.gxkj.demo.netty.proxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel(); f.addListener(new ChannelFutureListener() { @Override/* w w w . ja v a2 s . com*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:com.gxkj.demo.netty.proxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { if (outboundChannel.isActive()) { outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override//from w w w.j a va2 s . c om public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } }
From source file:com.hazelcast.openshift.TunnelClientAcceptor.java
License:Open Source License
private Channel createRemoteChannel(Channel socket) throws Exception { Bootstrap bootstrap = createBootstrap(socket); ChannelFuture connectFuture = bootstrap.connect(forwardHost, forwardPort); ChannelFuture future = connectFuture.sync(); if (!future.isSuccess()) { return null; }/*from ww w . ja v a 2s.c o m*/ return future.channel(); }
From source file:com.hazelcast.simulator.protocol.connector.AbstractServerConnector.java
License:Open Source License
@Override public void start() { messageQueueThread.start();/*from www . j a v a2s . c o m*/ ServerBootstrap bootstrap = getServerBootstrap(); ChannelFuture future = bootstrap.bind().syncUninterruptibly(); channel = future.channel(); LOGGER.info(format("ServerConnector %s listens on %s", localAddress, channel.localAddress())); }
From source file:com.hazelcast.simulator.protocol.connector.ClientConnector.java
License:Open Source License
public void start() { Bootstrap bootstrap = getBootstrap(); ChannelFuture future = bootstrap.connect().syncUninterruptibly(); channel = future.channel(); LOGGER.info(format("ClientConnector %s -> %s sends to %s", localAddress, remoteAddress, channel.remoteAddress()));//w w w. j a v a 2 s. c om }
From source file:com.hazelcast.simulator.protocol.handler.ConnectionHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { if (!(obj instanceof ByteBuf)) { return;/*from w w w .j ava 2 s.c om*/ } ByteBuf buf = (ByteBuf) obj; if (buf.readableBytes() < MINIMUM_BYTE_BUFFER_SIZE) { return; } if (!isSimulatorMessage(buf) && !isResponse(buf)) { LOGGER.warn(format("Invalid connection from %s (no magic bytes found)", ctx.channel().remoteAddress())); ctx.close(); return; } // the connection is valid so we remove this handler and forward the buffer to the pipeline LOGGER.info(format("Valid connection from %s (magic bytes found)", ctx.channel().remoteAddress())); isConnectionValid.countDown(); ctx.pipeline().remove(this); ctx.fireChannelRead(obj); ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connectionListener.disconnected(future.channel()); } }); connectionListener.connected(ctx.channel()); }
From source file:com.hazelcast.simulator.protocol.handler.ConnectionListenerHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override// w w w. jav a2s.co m public void operationComplete(ChannelFuture future) throws Exception { connectionListener.disconnected(future.channel()); } }); connectionListener.connected(ctx.channel()); }
From source file:com.heelenyc.research.netty.basic.TimeClient.java
License:Apache License
/** * @param port// w ww. j a v a2 s . co m * @param host * @throws Exception */ public void connect(int port, String host) throws Exception { // ?NIO 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 TimeClientHandler()); } }); // ?? ChannelFuture f = b.connect(host, port).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:com.heliosapm.streams.onramp.OnRampBoot.java
License:Apache License
/** * Creates a new OnRampBoot//from w w w . j a va 2 s . c o m * @param appConfig The application configuration */ public OnRampBoot(final Properties appConfig) { final String jmxmpUri = ConfigurationHelper.getSystemThenEnvProperty("jmx.jmxmp.uri", "jmxmp://0.0.0.0:1893", appConfig); JMXHelper.fireUpJMXMPServer(jmxmpUri); MessageForwarder.initialize(appConfig); port = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.port", 8091, appConfig); bindInterface = ConfigurationHelper.getSystemThenEnvProperty("onramp.network.bind", "0.0.0.0", appConfig); bindSocket = new InetSocketAddress(bindInterface, port); workerThreads = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.worker_threads", CORES * 2, appConfig); connectTimeout = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sotimeout", 0, appConfig); backlog = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.backlog", 3072, appConfig); writeSpins = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.writespins", 16, appConfig); recvBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.recbuffer", 43690, appConfig); sendBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sendbuffer", 8192, appConfig); disableEpoll = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.epoll.disable", false, appConfig); async = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.async_io", true, appConfig); tcpNoDelay = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.tcp_no_delay", true, appConfig); keepAlive = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.keep_alive", true, appConfig); reuseAddress = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.reuse_address", true, appConfig); tcpPipelineFactory = new PipelineFactory(appConfig); udpPipelineFactory = new UDPPipelineFactory(); tcpServerBootstrap.handler(new LoggingHandler(getClass(), LogLevel.INFO)); tcpServerBootstrap.childHandler(tcpPipelineFactory); // Set the child options tcpServerBootstrap.childOption(ChannelOption.ALLOCATOR, BufferManager.getInstance().getAllocator()); tcpServerBootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay); tcpServerBootstrap.childOption(ChannelOption.SO_KEEPALIVE, keepAlive); tcpServerBootstrap.childOption(ChannelOption.SO_RCVBUF, recvBuffer); tcpServerBootstrap.childOption(ChannelOption.SO_SNDBUF, sendBuffer); tcpServerBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, writeSpins); // Set the server options tcpServerBootstrap.option(ChannelOption.SO_BACKLOG, backlog); tcpServerBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); tcpServerBootstrap.option(ChannelOption.SO_RCVBUF, recvBuffer); tcpServerBootstrap.option(ChannelOption.SO_TIMEOUT, connectTimeout); final StringBuilder tcpUri = new StringBuilder("tcp"); final StringBuilder udpUri = new StringBuilder("udp"); if (IS_LINUX && !disableEpoll) { bossExecutorThreadFactory = new ExecutorThreadFactory("EpollServerBoss", true); bossGroup = new EpollEventLoopGroup(1, (ThreadFactory) bossExecutorThreadFactory); workerExecutorThreadFactory = new ExecutorThreadFactory("EpollServerWorker", true); workerGroup = new EpollEventLoopGroup(workerThreads, (ThreadFactory) workerExecutorThreadFactory); tcpChannelType = EpollServerSocketChannel.class; udpChannelType = EpollDatagramChannel.class; tcpUri.append("epoll"); udpUri.append("epoll"); } else { bossExecutorThreadFactory = new ExecutorThreadFactory("NioServerBoss", true); bossGroup = new NioEventLoopGroup(1, bossExecutorThreadFactory); workerExecutorThreadFactory = new ExecutorThreadFactory("NioServerWorker", true); workerGroup = new NioEventLoopGroup(workerThreads, workerExecutorThreadFactory); tcpChannelType = NioServerSocketChannel.class; udpChannelType = NioDatagramChannel.class; tcpUri.append("nio"); udpUri.append("nio"); } tcpUri.append("://").append(bindInterface).append(":").append(port); udpUri.append("://").append(bindInterface).append(":").append(port); URI u = null; try { u = new URI(tcpUri.toString()); } catch (URISyntaxException e) { log.warn("Failed TCP server URI const: [{}]. Programmer Error", tcpUri, e); } tcpServerURI = u; try { u = new URI(udpUri.toString()); } catch (URISyntaxException e) { log.warn("Failed UDP server URI const: [{}]. Programmer Error", udpUri, e); } udpServerURI = u; log.info(">>>>> Starting OnRamp TCP Listener on [{}]...", tcpServerURI); log.info(">>>>> Starting OnRamp UDP Listener on [{}]...", udpServerURI); final ChannelFuture cf = tcpServerBootstrap.channel(tcpChannelType).group(bossGroup, workerGroup) .bind(bindSocket).awaitUninterruptibly() .addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(final Future<? super Void> f) throws Exception { log.info("<<<<< OnRamp TCP Listener on [{}] Started", tcpServerURI); }; }).awaitUninterruptibly(); final ChannelFuture ucf = udpBootstrap.channel(udpChannelType).group(workerGroup) .option(ChannelOption.SO_BROADCAST, true).handler(new UDPPipelineFactory()).bind(bindSocket) .awaitUninterruptibly().addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(final Future<? super Void> f) throws Exception { log.info("<<<<< OnRamp UDP Listener on [{}] Started", udpServerURI); }; }).awaitUninterruptibly(); tcpServerChannel = cf.channel(); udpServerChannel = ucf.channel(); tcpCloseFuture = tcpServerChannel.closeFuture(); udpCloseFuture = udpServerChannel.closeFuture(); Runtime.getRuntime().addShutdownHook(shutdownHook); }
From source file:com.heliosapm.streams.tracing.writers.NetWriter.java
License:Apache License
/** * Attempts to connect to the specified host/port and updates the channel tracking structures accordingly * @param uri The <b><code>host:port</code></b> pair *//*from w w w . j a v a 2 s . co m*/ protected void connect(final String uri) { String _host = null; int _port = -1; try { final String[] hostPort = StringHelper.splitString(uri, ':', true); _host = hostPort[0]; _port = Integer.parseInt(hostPort[1]); } catch (Exception ex) { log.warn("Invalid Remote URI [{}]", uri); } final ChannelFuture cf = bootstrap.connect(_host, _port); cf.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(final Future<Void> f) throws Exception { if (f.isSuccess()) { final Channel channel = cf.channel(); ChannelFuture closeFuture = channel.closeFuture(); closeFutures.put(uri, closeFuture); disconnected.remove(new DelayedReconnect(uri)); closeFuture.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(final Future<? super Void> future) throws Exception { closeFutures.remove(uri); if (group.isShutdown() || group.isShuttingDown() || group.isTerminated()) { /* No Op */ } else { final DelayedReconnect dc = new DelayedReconnect(uri); if (!disconnected.contains(dc)) { disconnected.add(dc); } } channels.remove(channel); // may have been removed already fireDisconnected(); } }); channels.add(channel); fireConnected(); log.info("Channel [{}] connected to [{}]", channel, uri); } else { final DelayedReconnect dc = new DelayedReconnect(uri); if (!disconnected.contains(dc)) { disconnected.add(dc); } log.warn("Channel failed to connect to [{}]", uri, f.cause()); } } }); }