List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java
License:Apache License
@Override public CompletableFuture<Void> connect() { final CompletableFuture<Void> future = new CompletableFuture<>(); if (channel != null) { future.complete(null);/*from ww w .ja va 2s . co m*/ return future; } final SslContext sslContext; if (protocol.isSsl()) { try { sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } catch (SSLException e) { future.completeExceptionally(e); return future; } } else { sslContext = null; } final EventLoopGroup group = new NioEventLoopGroup(protocol.getThreads()); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslContext != null) { pipeline.addLast( sslContext.newHandler(channel.alloc(), protocol.getHost(), protocol.getPort())); } pipeline.addLast(new ObjectEncoder(), new ObjectDecoder( ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())), new TcpProtocolClientHandler(TcpProtocolClient.this)); } }); if (protocol.getSendBufferSize() > -1) { bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize()); } if (protocol.getReceiveBufferSize() > -1) { bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize()); } if (protocol.getTrafficClass() > -1) { bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass()); } bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay()); bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger()); bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout()); bootstrap.connect(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { channel = channelFuture.channel(); future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } } }); return future; }
From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java
License:Apache License
@Override public CompletableFuture<Void> close() { final CompletableFuture<Void> future = new CompletableFuture<>(); if (channel != null) { channel.close().addListener(new ChannelFutureListener() { @Override/*from w ww.j a va 2 s . co m*/ public void operationComplete(ChannelFuture channelFuture) throws Exception { channel = null; if (channelFuture.isSuccess()) { future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } } }); } else { future.complete(null); } return future; }
From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java
License:Apache License
@Override public CompletableFuture<Void> start() { final CompletableFuture<Void> future = new CompletableFuture<>(); // TODO: Configure proper SSL trust store. final SslContext sslContext; if (protocol.isSsl()) { try {//from w ww .j a va 2 s. co m SelfSignedCertificate ssc = new SelfSignedCertificate(); sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (SSLException | CertificateException e) { future.completeExceptionally(e); return future; } } else { sslContext = null; } final EventLoopGroup serverGroup = new NioEventLoopGroup(); final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads()); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(channel.alloc())); } pipeline.addLast(new ObjectEncoder(), new ObjectDecoder( ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())), new TcpProtocolServerHandler(TcpProtocolServer.this)); } }).option(ChannelOption.SO_BACKLOG, 128); if (protocol.getSendBufferSize() > -1) { bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize()); } if (protocol.getReceiveBufferSize() > -1) { bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize()); } bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay()); bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress()); bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive()); bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog()); if (protocol.getTrafficClass() > -1) { bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass()); } bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // Bind and start to accept incoming connections. bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { workerGroup.shutdownGracefully(); } }); if (channelFuture.isSuccess()) { channel = channelFuture.channel(); future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } } }); return future; }
From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java
License:Apache License
@Override public CompletableFuture<Void> stop() { final CompletableFuture<Void> future = new CompletableFuture<>(); if (channel != null) { channel.close().addListener(new ChannelFutureListener() { @Override// w ww .j a va 2 s . c om public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { future.complete(null); } else { future.completeExceptionally(channelFuture.cause()); } } }); } else { future.complete(null); } return future; }
From source file:net.petercashel.nettyCore.client.clientCore.java
License:Apache License
/** * Initializes a Client Connection//from w w w . j a v a2 s .com * * @param addr * - String address to connect to * @param port * - int Port number to connect to * @throws Exception */ public static void initializeConnection(final String addr, final int port) throws Exception { _host = addr; _port = port; PacketRegistry.setupRegistry(); PacketRegistry.Side = side; if (UseSSL) SSLContextProvider.SetupSSL(); 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(); p.addLast("readTimeoutHandler", new ReadTimeoutHandler(300)); if (UseSSL && !SSLContextProvider.selfSigned) p.addLast("ssl", getClientSSLHandler(addr, port)); if (UseSSL && SSLContextProvider.selfSigned) p.addLast("ssl", SSLContextProvider.getSelfClient().newHandler(ch.alloc(), addr, port)); p.addLast("InboundOutboundClientHandler", new ClientConnectionHander()); } }); // Make the connection attempt. ChannelFuture f = b.connect(addr, port).sync(); f.awaitUninterruptibly(2000, TimeUnit.MILLISECONDS); if (!f.isSuccess()) throw new RuntimeException("Failed to connect"); // if a wait option was selected and the connect did not fail, // the Date can now be sent. System.out.println("Client Core Connected!"); connection = f.channel(); connClosed = false; // Initiate the Ping->Pong->PingPong Packet test. PacketRegistry.pack(new PingPacket()) .sendPacket(connection.pipeline().context("InboundOutboundClientHandler")); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); System.out.println("Connection Closed"); connClosed = true; } }
From source file:net.petercashel.nettyCore.clientUDS.clientCoreUDS.java
License:Apache License
public static void initializeConnection(File socket) throws Exception { PacketRegistry.setupRegistry();/*from w w w. j ava 2 s . com*/ PacketRegistry.Side = side; group = new EpollEventLoopGroup(); try { Bootstrap b = new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(group).channel(EpollDomainSocketChannel.class) .handler(new ChannelInitializer<EpollDomainSocketChannel>() { @Override protected void initChannel(EpollDomainSocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("InboundOutboundClientHandler", new ClientUDSConnectionHander()); } }); } }.newInstance(); // Make the connection attempt. ChannelFuture f = b.connect(newSocketAddress(socket)).sync(); f.awaitUninterruptibly(2000, TimeUnit.MILLISECONDS); if (!f.isSuccess()) throw new RuntimeException("Failed to connect"); // if a wait option was selected and the connect did not fail, // the Date can now be sent. System.out.println("Client UDS Connected!"); connection = f.channel(); connClosed = false; // Send GetHistoryPacket PacketRegistry.pack(new GetHistoryPacket()).sendPacket(connection); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); System.out.println("Connection Closed"); connClosed = true; } }
From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java
License:Open Source License
private boolean connectToEntrainer() throws InterruptedException { ChannelFuture cf = bootstrap.connect(ipAddress, port).sync(); setOutputText(cf.isSuccess() ? "Connected to Entrainer on host " + ipAddress + " and port " + port : "Cannot connect to Entrainer on host " + ipAddress + " and port " + port); if (cf.isSuccess()) { channel = cf.channel();/*w ww . ja v a 2 s. com*/ } return cf.isSuccess(); }
From source file:net.sourceforge.entrainer.socket.EntrainerSocketManager.java
License:Open Source License
/** * Binds the socket to the port specified in {@link Settings}. * * @throws IOException//from w w w. ja va2 s .c o m * Signals that an I/O exception has occurred. * @throws InvalidPortNumberException * if the port number <= 0. */ public void bind() throws IOException, InvalidPortNumberException { if (isBound()) return; String ipAddress = Settings.getInstance().getSocketIPAddress(); if (ipAddress == null || ipAddress.trim().length() == 0) initIPAddress(); ipAddress = Settings.getInstance().getSocketIPAddress(); if (bootstrap == null) initAcceptor(); int port = Settings.getInstance().getSocketPort(); if (port <= 0) throw new InvalidPortNumberException(port); ChannelFuture cf = bootstrap.bind(ipAddress, port).syncUninterruptibly(); if (cf.isSuccess()) { channel = cf.channel(); } else { throw new RuntimeException("Could not bind to host " + ipAddress + " and port " + port, cf.cause()); } }
From source file:net.tomp2p.connection.ChannelServer.java
License:Apache License
/** * Handles the waiting and returning the channel. * /*from www . j a v a2s . c om*/ * @param future * The future to wait for * @return The channel or null if we failed to bind. */ private boolean handleFuture(final ChannelFuture future) { try { future.await(); } catch (InterruptedException e) { if (LOG.isWarnEnabled()) { LOG.warn("could not start UPD server", e); } return false; } boolean success = future.isSuccess(); if (success) { return true; } else { LOG.debug("binding not successful", future.cause()); return false; } }
From source file:net.tomp2p.connection.Sender.java
License:Apache License
/** * After connecting, we check if the connect was successful. * //w w w . j a v a 2 s .c o m * @param futureResponse * The future to set the response * @param message * The message to send * @param channelFuture * the future of the connect * @param fireAndForget * True, if we don't expect a message */ public void afterConnect(final FutureResponse futureResponse, final Message message, final ChannelFuture channelFuture, final boolean fireAndForget) { if (channelFuture == null) { futureResponse.failed("could not create a " + (message.isUdp() ? "UDP" : "TCP") + " channel"); return; } LOG.debug("about to connect to {} with channel {}, ff={}", message.recipient(), channelFuture.channel(), fireAndForget); final Cancel connectCancel = createCancel(channelFuture); futureResponse.addCancel(connectCancel); channelFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { futureResponse.removeCancel(connectCancel); if (future.isSuccess()) { final ChannelFuture writeFuture = future.channel().writeAndFlush(message); afterSend(writeFuture, futureResponse, fireAndForget); } else { LOG.debug("Channel creation failed", future.cause()); futureResponse.failed("Channel creation failed " + future.channel() + "/" + future.cause()); // may have been closed by the other side, // or it may have been canceled from this side if (!(future.cause() instanceof CancellationException) && !(future.cause() instanceof ClosedChannelException) && !(future.cause() instanceof ConnectException)) { LOG.warn("Channel creation failed to {} for {}", future.channel(), message); } } } }); }