List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:gwlpr.protocol.handshake.HandshakeHandler.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN); switch (server) { case LoginServer: // client version: {/*ww w .j a v a 2 s. c om*/ // lengthcheck if (buf.readableBytes() < (P000_ClientVersion.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_ClientVersion.Header header = P000_ClientVersion.serializeHeader(buf); // check the header if (header == null || !P000_ClientVersion.check(header)) { return; } // get the data P000_ClientVersion.Payload payload = P000_ClientVersion.serializePayload(buf); LOGGER.debug(String.format("Got the client version: %d", payload.ClientVersion)); } break; case GameServer: // verify client: { // lengthcheck if (buf.readableBytes() < (P000_VerifyClient.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_VerifyClient.Header header = P000_VerifyClient.serializeHeader(buf); // check the header if (header == null || !P000_VerifyClient.check(header)) { return; } // get the data verifyClient = P000_VerifyClient.serializePayload(buf); LOGGER.debug(String.format("Got the verify client packet.")); } break; } // client seed: // get the header P000_ClientSeed.Header header = P000_ClientSeed.serializeHeader(buf); // check the header if (header == null || !P000_ClientSeed.check(header)) { return; } // get the data P000_ClientSeed.Payload payload = P000_ClientSeed.serializePayload(buf); LOGGER.debug("Got the client seed packet."); // INITIALIZE ENCRYPTION WITH THE CLIENT SEED PAYLOAD // generate the shared key byte[] sharedKeyBytes = EncryptionUtils.generateSharedKey(payload.ClientPublicKey); // start RC4 key generation byte[] randomBytes = new byte[20]; new SecureRandom().nextBytes(randomBytes); final byte[] rc4Key = EncryptionUtils.hash(randomBytes); // encrypt the RC4 key before sending it to the client byte[] xoredRandomBytes = EncryptionUtils.XOR(randomBytes, sharedKeyBytes); // INITIALIZATION OF ENCRYPTION DONE // we can set the RC4 decoder now... if encryption is enabled if (encryption == EncryptionOptions.Enable) { RC4Codec.Decoder decoder = new RC4Codec.Decoder(rc4Key); ctx.pipeline().addFirst(decoder); LOGGER.debug("RC4Decoder added to pipeline."); } // now send the server seed packet P001_ServerSeed serverSeed = new P001_ServerSeed(); serverSeed.setEncryptedRC4Key(xoredRandomBytes); buf = ctx.alloc().buffer(70).order(ByteOrder.LITTLE_ENDIAN); serverSeed.serializeInto(buf); ChannelFuture cf = ctx.writeAndFlush(buf); // also remove this handler ctx.pipeline().remove(this); // set the RC4 encoder only after the serverseed packet has been send! cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (encryption == EncryptionOptions.Enable) { // add the rc4 codec if encryption is enabled RC4Codec.Encoder encoder = new RC4Codec.Encoder(rc4Key); ctx.pipeline().addFirst(encoder); LOGGER.debug("RC4Encoder added to pipeline."); } // tell the channel's context that handshake has been done ctx.channel().attr(GameAppContextKey.KEY).get() .trigger(new HandShakeDoneEvent(ctx.channel(), verifyClient)); } }); }
From source file:io.advantageous.conekt.http.impl.ServerConnection.java
License:Open Source License
NetSocket createNetSocket() { NetSocketImpl socket = new NetSocketImpl(vertx, channel, context, server.getSslHelper(), false, metrics, metric);/*from w w w .ja va 2s . c o m*/ Map<Channel, NetSocketImpl> connectionMap = new HashMap<>(1); connectionMap.put(channel, socket); // Flush out all pending data endReadAndFlush(); // remove old http handlers and replace the old handler with one that handle plain sockets ChannelPipeline pipeline = channel.pipeline(); ChannelHandler compressor = pipeline.get(HttpChunkContentCompressor.class); if (compressor != null) { pipeline.remove(compressor); } pipeline.remove("httpDecoder"); if (pipeline.get("chunkedWriter") != null) { pipeline.remove("chunkedWriter"); } channel.pipeline().replace("handler", "handler", new ConektNetHandler(connectionMap) { @Override public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception { // remove from the real mapping server.removeChannel(channel); super.exceptionCaught(chctx, t); } @Override public void channelInactive(ChannelHandlerContext chctx) throws Exception { // remove from the real mapping server.removeChannel(channel); super.channelInactive(chctx); } @Override public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception { if (msg instanceof HttpContent) { ReferenceCountUtil.release(msg); return; } super.channelRead(chctx, msg); } }); // check if the encoder can be removed yet or not. if (lastWriteFuture == null) { channel.pipeline().remove("httpEncoder"); } else { lastWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel.pipeline().remove("httpEncoder"); } }); } return socket; }
From source file:io.aos.netty5.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void messageReceived(final ChannelHandlerContext ctx, final SocksRequest message) throws Exception { if (message instanceof Socks4CmdRequest) { final Socks4CmdRequest request = (Socks4CmdRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override/*from w w w .j a va2s .c o m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.SUCCESS)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CmdRequest) { final Socks5CmdRequest request = (Socks5CmdRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel() .writeAndFlush( new Socks5CmdResponse(Socks5CmdStatus.SUCCESS, request.addressType())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush( new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:io.codis.nedis.NedisClientBuilder.java
License:Apache License
public Future<NedisClientImpl> connect(SocketAddress remoteAddress) { validateGroupConfig();//from w ww . j ava2s. c om Bootstrap b = new Bootstrap().group(group).channel(channelClass).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new RedisResponseDecoder(), new RedisDuplexHandler(TimeUnit.MILLISECONDS.toNanos(timeoutMs))); } }); if (timeoutMs > 0) { b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) Math.min(Integer.MAX_VALUE, timeoutMs)); } ChannelFuture f = b.connect(remoteAddress); final Promise<NedisClientImpl> promise = f.channel().eventLoop().newPromise(); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { promise.trySuccess(new NedisClientImpl(future.channel(), pool)); } else { promise.tryFailure(future.cause()); } } }); return promise; }
From source file:io.dyn.net.tcp.TcpClient.java
License:Apache License
@SuppressWarnings({ "unchecked" }) @Override/*from ww w. ja v a2s.com*/ public T start() { if (!started.get()) { on(Lifecycle.STOP, new CompletionHandler() { @Override protected void complete() { if (channelFuture.awaitUninterruptibly(15, TimeUnit.SECONDS)) { channelFuture.getChannel().close(); } started.set(false); } }); bootstrap.setOption("child.keepAlive", keepAlive); bootstrap.setOption("child.receiveBufferSize", Buffer.SMALL_BUFFER_SIZE); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { final ChannelPipeline pipeline = Channels.pipeline(); TcpClient.this.configurePipeline(pipeline); return pipeline; } }); try { channelFuture = bootstrap.connect(new InetSocketAddress(InetAddress.getByName(host), port)); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { started.set(true); event(Lifecycle.START); } else { Throwable t = channelFuture.getCause(); event(Events.classToEventExpression(t.getClass()), t); } } }); } catch (UnknownHostException e) { event(Events.classToEventExpression(e.getClass()), e); } } return (T) this; }
From source file:io.dyn.net.tcp.TcpClient.java
License:Apache License
@SuppressWarnings({ "unchecked" }) @Override/*from w w w . j a v a 2s. c o m*/ public T stop() { if (started.get()) { channelFuture.getChannel().close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { started.set(false); event(Lifecycle.STOP); } }); } return (T) this; }
From source file:io.dyn.net.tcp.TcpServer.java
License:Apache License
@SuppressWarnings({ "unchecked" }) @Override// ww w. ja va 2 s. c om public T stop() { //LOG.info("Stopping..."); if (null != channel) { channel.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { started.set(false); event(Lifecycle.STOP); } }); } return (T) this; }
From source file:io.gomint.proxprox.network.DownstreamConnection.java
License:BSD License
/** * Create a new AbstractConnection to a server. * * @param proxProx The proxy instance * @param upstreamConnection The upstream connection which requested to connect to this downstream * @param ip The ip of the server we want to connect to * @param port The port of the server we want to connect to *//* ww w . j a va2 s .co m*/ DownstreamConnection(ProxProxProxy proxProx, UpstreamConnection upstreamConnection, String ip, int port) { this.upstreamConnection = upstreamConnection; this.proxProx = proxProx; this.ip = ip; this.port = port; // Check if we use UDP or TCP for downstream connections if (proxProx.getConfig().isUseTCP()) { io.netty.bootstrap.Bootstrap bootstrap = Initializer.buildBootstrap(this.upstreamConnection, ip, port, new Consumer<ConnectionHandler>() { @Override public void accept(ConnectionHandler connectionHandler) { DownstreamConnection.this.tcpConnection = connectionHandler; // There are no batches in TCP connectionHandler.onData(DownstreamConnection.this::handlePacket); connectionHandler.whenDisconnected(new Consumer<Void>() { @Override public void accept(Void aVoid) { if (upstreamConnection.isConnected()) { LOGGER.info("Disconnected downstream..."); if (!DownstreamConnection.this.manualClose) { DownstreamConnection.this.close(true, "Server disconnected"); // Check if we need to disconnect upstream if (DownstreamConnection.this .equals(upstreamConnection.getDownStream())) { if (upstreamConnection.getPendingDownStream() != null || upstreamConnection.connectToLastKnown()) { return; } else { upstreamConnection.disconnect("The Server has gone down"); } } else { upstreamConnection.resetPendingDownStream(); } } } } }); DownstreamConnection.this.upstreamConnection .onDownStreamConnected(DownstreamConnection.this); } }); bootstrap.connect(this.ip, this.port).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (!channelFuture.isSuccess()) { LOGGER.warn("Could not connect to {}:{}", DownstreamConnection.this.ip, DownstreamConnection.this.port, channelFuture.cause()); DownstreamConnection.this.upstreamConnection.resetPendingDownStream(); } } }); } else { this.initDecompressor(); this.connection = new ClientSocket(); this.connection.setMojangModificationEnabled(true); this.connection.setEventHandler((socket, socketEvent) -> { LOGGER.debug("Got socketEvent: " + socketEvent.getType().name()); switch (socketEvent.getType()) { case CONNECTION_ATTEMPT_SUCCEEDED: // We got accepted *yay* DownstreamConnection.this.setup(); DownstreamConnection.this.upstreamConnection.onDownStreamConnected(DownstreamConnection.this); break; case CONNECTION_CLOSED: case CONNECTION_DISCONNECTED: LOGGER.info("Disconnected downstream..."); if (!DownstreamConnection.this.manualClose) { DownstreamConnection.this.updateIncoming(socketEvent.getConnection()); DownstreamConnection.this.close(true, "Raknet disconnected"); // Check if we need to disconnect upstream if (DownstreamConnection.this.equals(upstreamConnection.getDownStream())) { if (upstreamConnection.getPendingDownStream() != null || upstreamConnection.connectToLastKnown()) { return; } else { upstreamConnection.disconnect("The Server has gone down"); } } else { upstreamConnection.resetPendingDownStream(); } } break; default: break; } }); try { this.connection.initialize(); } catch (SocketException e) { LOGGER.warn("Could not connect to {}:{}", this.ip, this.port, e); } this.connection.connect(ip, port); } }
From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java
License:Apache License
@Test @SuppressWarnings("unchecked") // List cast public void protectShouldRoundtrip() throws Exception { doHandshake();/* w ww . ja v a 2 s . c om*/ // Write the message 1 character at a time. The message should be buffered // and not interfere with the handshake. final AtomicInteger writeCount = new AtomicInteger(); String message = "hello"; for (int ix = 0; ix < message.length(); ++ix) { ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8); @SuppressWarnings("unused") // go/futurereturn-lsc Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { writeCount.incrementAndGet(); } } }); } channel.flush(); // Capture the protected data written to the wire. assertEquals(1, channel.outboundMessages().size()); ByteBuf protectedData = channel.readOutbound(); assertEquals(message.length(), writeCount.get()); // Read the protected message at the server and verify it matches the original message. TsiFrameProtector serverProtector = serverHandshaker.createFrameProtector(channel.alloc()); List<ByteBuf> unprotected = new ArrayList<>(); serverProtector.unprotect(protectedData, (List<Object>) (List<?>) unprotected, channel.alloc()); // We try our best to remove the HTTP2 handler as soon as possible, but just by constructing it // a settings frame is written (and an HTTP2 preface). This is hard coded into Netty, so we // have to remove it here. See {@code Http2ConnectionHandler.PrefaceDecode.sendPreface}. int settingsFrameLength = 9; CompositeByteBuf unprotectedAll = new CompositeByteBuf(channel.alloc(), false, unprotected.size() + 1, unprotected); ByteBuf unprotectedData = unprotectedAll.slice(settingsFrameLength, message.length()); assertEquals(message, unprotectedData.toString(UTF_8)); // Protect the same message at the server. final AtomicReference<ByteBuf> newlyProtectedData = new AtomicReference<>(); serverProtector.protectFlush(Collections.singletonList(unprotectedData), new Consumer<ByteBuf>() { @Override public void accept(ByteBuf buf) { newlyProtectedData.set(buf); } }, channel.alloc()); // Read the protected message at the client and verify that it matches the original message. channel.writeInbound(newlyProtectedData.get()); assertEquals(1, channel.inboundMessages().size()); assertEquals(message, channel.<ByteBuf>readInbound().toString(UTF_8)); }
From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java
License:Apache License
@Test public void flushShouldFailAllPromises() throws Exception { doHandshake();/* www. j a va 2 s .c om*/ channel.pipeline().addFirst(new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { throw new Exception("Fake exception"); } }); // Write the message 1 character at a time. String message = "hello"; final AtomicInteger failures = new AtomicInteger(); for (int ix = 0; ix < message.length(); ++ix) { ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8); @SuppressWarnings("unused") // go/futurereturn-lsc Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { failures.incrementAndGet(); } } }); } channel.flush(); // Verify that the promises fail. assertEquals(message.length(), failures.get()); }