Search in sources :

Example 66 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project study-by-myself by Howinfun.

the class NettyServer method main.

public static void main(String[] args) throws Exception {
    NioEventLoopGroup boss = new NioEventLoopGroup();
    NioEventLoopGroup work = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(boss, work).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(NioSocketChannel channel) throws Exception {
            channel.pipeline().addLast(new ProtobufVarint32FrameDecoder()).addLast(new ProtobufDecoder(JsonMsgProto.Msg.getDefaultInstance())).addLast(new ProtobufProcessorHandler());
        }
    });
    serverBootstrap.bind("127.0.0.1", 8080).addListener(new GenericFutureListener<Future<? super Void>>() {

        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.isSuccess()) {
                System.out.println("启动成功!");
            } else {
                System.out.println("启动失败!");
            }
        }
    }).sync();
    ThreadUtil.sleep(Integer.MAX_VALUE);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ProtobufDecoder(io.netty.handler.codec.protobuf.ProtobufDecoder) Future(io.netty.util.concurrent.Future) ProtobufVarint32FrameDecoder(io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 67 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project Minecraft-SlientClient-Hack by YouNeverKnow00.

the class NetworkSystem method networkTick.

/**
 * Will try to process the packets received by each NetworkManager, gracefully manage processing failures and cleans
 * up dead connections
 */
public void networkTick() {
    synchronized (this.networkManagers) {
        Iterator<NetworkManager> iterator = this.networkManagers.iterator();
        while (iterator.hasNext()) {
            final NetworkManager networkmanager = iterator.next();
            if (!networkmanager.hasNoChannel()) {
                if (networkmanager.isChannelOpen()) {
                    try {
                        networkmanager.processReceivedPackets();
                    } catch (Exception exception) {
                        if (networkmanager.isLocalChannel()) {
                            CrashReport crashreport = CrashReport.makeCrashReport(exception, "Ticking memory connection");
                            CrashReportCategory crashreportcategory = crashreport.makeCategory("Ticking connection");
                            crashreportcategory.setDetail("Connection", new ICrashReportDetail<String>() {

                                public String call() throws Exception {
                                    return networkmanager.toString();
                                }
                            });
                            throw new ReportedException(crashreport);
                        }
                        LOGGER.warn("Failed to handle packet for {}", networkmanager.getRemoteAddress(), exception);
                        final TextComponentString textcomponentstring = new TextComponentString("Internal server error");
                        networkmanager.sendPacket(new SPacketDisconnect(textcomponentstring), new GenericFutureListener<Future<? super Void>>() {

                            public void operationComplete(Future<? super Void> p_operationComplete_1_) throws Exception {
                                networkmanager.closeChannel(textcomponentstring);
                            }
                        });
                        networkmanager.disableAutoRead();
                    }
                } else {
                    iterator.remove();
                    networkmanager.checkDisconnected();
                }
            }
        }
    }
}
Also used : CrashReport(net.minecraft.crash.CrashReport) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ICrashReportDetail(net.minecraft.crash.ICrashReportDetail) SPacketDisconnect(net.minecraft.network.play.server.SPacketDisconnect) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ReportedException(net.minecraft.util.ReportedException) IOException(java.io.IOException) ChannelException(io.netty.channel.ChannelException) CrashReportCategory(net.minecraft.crash.CrashReportCategory) ReportedException(net.minecraft.util.ReportedException) TextComponentString(net.minecraft.util.text.TextComponentString)

Example 68 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project CumServerPro by MCUmbrella.

the class NetworkDispatcher method kickWithMessage.

private void kickWithMessage(String message) {
    FMLLog.log.error("Network Disconnect: {}", message);
    final TextComponentString TextComponentString = new TextComponentString(message);
    if (side == Side.CLIENT) {
        manager.closeChannel(TextComponentString);
    } else {
        manager.sendPacket(new SPacketDisconnect(TextComponentString), new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> result) {
                manager.closeChannel(TextComponentString);
            }
        }, (GenericFutureListener<? extends Future<? super Void>>[]) null);
    }
    manager.channel().config().setAutoRead(false);
}
Also used : Future(io.netty.util.concurrent.Future) SPacketDisconnect(net.minecraft.network.play.server.SPacketDisconnect) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) TextComponentString(net.minecraft.util.text.TextComponentString)

Example 69 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project pollen by MoonflowerTeam.

the class PollinatedFabricLoginChannel method processClient.

private CompletableFuture<@Nullable FriendlyByteBuf> processClient(Minecraft client, ClientHandshakePacketListenerImpl listener, FriendlyByteBuf data, Consumer<GenericFutureListener<? extends Future<? super Void>>> listenerAdder) {
    CompletableFuture<FriendlyByteBuf> future = new CompletableFuture<>();
    NetworkRegistry.processMessage(this.deserialize(data, PollinatedPacketDirection.LOGIN_CLIENTBOUND), new PollinatedFabricLoginPacketContext(pkt -> {
        try {
            future.complete(this.serialize(pkt, PollinatedPacketDirection.LOGIN_SERVERBOUND));
        } catch (Throwable t) {
            t.printStackTrace();
            future.completeExceptionally(t);
        }
    }, listener.getConnection(), __ -> {
    }, PollinatedPacketDirection.LOGIN_CLIENTBOUND), this.clientMessageHandler.get().get());
    return future;
}
Also used : FriendlyByteBuf(net.minecraft.network.FriendlyByteBuf) FabricLoader(net.fabricmc.loader.api.FabricLoader) ResourceLocation(net.minecraft.resources.ResourceLocation) PollinatedLoginNetworkChannel(gg.moonflower.pollen.api.network.PollinatedLoginNetworkChannel) PacketSender(net.fabricmc.fabric.api.networking.v1.PacketSender) NetworkRegistry(gg.moonflower.pollen.api.registry.NetworkRegistry) PollinatedLoginPacket(gg.moonflower.pollen.api.network.packet.login.PollinatedLoginPacket) CompletableFuture(java.util.concurrent.CompletableFuture) FriendlyByteBuf(net.minecraft.network.FriendlyByteBuf) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) PacketDeserializer(gg.moonflower.pollen.api.network.PacketDeserializer) MinecraftServer(net.minecraft.server.MinecraftServer) Pair(org.apache.commons.lang3.tuple.Pair) Minecraft(net.minecraft.client.Minecraft) EnvType(net.fabricmc.api.EnvType) ClientLoginNetworking(net.fabricmc.fabric.api.client.networking.v1.ClientLoginNetworking) LoginQueryRequestS2CPacketAccessor(net.fabricmc.fabric.mixin.networking.accessor.LoginQueryRequestS2CPacketAccessor) ApiStatus(org.jetbrains.annotations.ApiStatus) PollinatedPacket(gg.moonflower.pollen.api.network.packet.PollinatedPacket) ServerLoginPacketListenerImpl(net.minecraft.server.network.ServerLoginPacketListenerImpl) PollinatedFabricLoginPacketContext(gg.moonflower.pollen.api.network.fabric.context.PollinatedFabricLoginPacketContext) ServerboundCustomQueryPacket(net.minecraft.network.protocol.login.ServerboundCustomQueryPacket) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ClientHandshakePacketListenerImpl(net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl) PollinatedPacketDirection(gg.moonflower.pollen.api.network.packet.PollinatedPacketDirection) ServerLoginConnectionEvents(net.fabricmc.fabric.api.networking.v1.ServerLoginConnectionEvents) PollinatedFabricPacketContext(gg.moonflower.pollen.api.network.fabric.context.PollinatedFabricPacketContext) Consumer(java.util.function.Consumer) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Packet(net.minecraft.network.protocol.Packet) Future(io.netty.util.concurrent.Future) ServerLoginNetworking(net.fabricmc.fabric.api.networking.v1.ServerLoginNetworking) ClientboundCustomQueryPacket(net.minecraft.network.protocol.login.ClientboundCustomQueryPacket) CompletableFuture(java.util.concurrent.CompletableFuture) PollinatedFabricLoginPacketContext(gg.moonflower.pollen.api.network.fabric.context.PollinatedFabricLoginPacketContext)

Example 70 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse-vertx.

the class NetClientImpl method connectInternal.

public void connectInternal(ProxyOptions proxyOptions, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, boolean useAlpn, boolean registerWriteHandlers, Promise<NetSocket> connectHandler, ContextInternal context, int remainingAttempts) {
    checkClosed();
    EventLoop eventLoop = context.nettyEventLoop();
    if (eventLoop.inEventLoop()) {
        Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoop);
        bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
        vertx.transport().configure(options, remoteAddress.isDomainSocket(), bootstrap);
        ChannelProvider channelProvider = new ChannelProvider(bootstrap, sslHelper, context).proxyOptions(proxyOptions);
        channelProvider.handler(ch -> connected(context, ch, connectHandler, remoteAddress, channelProvider.applicationProtocol(), registerWriteHandlers));
        io.netty.util.concurrent.Future<Channel> fut = channelProvider.connect(remoteAddress, peerAddress, serverName, ssl, useAlpn);
        fut.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) future -> {
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                boolean connectError = cause instanceof ConnectException || cause instanceof FileNotFoundException;
                if (connectError && (remainingAttempts > 0 || remainingAttempts == -1)) {
                    context.emit(v -> {
                        log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
                        vertx.setTimer(options.getReconnectInterval(), tid -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
                    });
                } else {
                    failed(context, null, cause, connectHandler);
                }
            }
        });
    } else {
        eventLoop.execute(() -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts));
    }
}
Also used : SSLContext(javax.net.ssl.SSLContext) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) ProxyOptions(io.vertx.core.net.ProxyOptions) ChannelGroup(io.netty.channel.group.ChannelGroup) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Predicate(java.util.function.Predicate) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) NetClientOptions(io.vertx.core.net.NetClientOptions) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) Channel(io.netty.channel.Channel) FileNotFoundException(java.io.FileNotFoundException) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.vertx.core.Future) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) ConnectException(java.net.ConnectException)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)70 Future (io.netty.util.concurrent.Future)44 ChannelFuture (io.netty.channel.ChannelFuture)32 Channel (io.netty.channel.Channel)19 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)18 IOException (java.io.IOException)18 List (java.util.List)15 InetSocketAddress (java.net.InetSocketAddress)13 ArrayList (java.util.ArrayList)13 Map (java.util.Map)12 ChannelOption (io.netty.channel.ChannelOption)10 Future (io.vertx.core.Future)10 Handler (io.vertx.core.Handler)10 ContextInternal (io.vertx.core.impl.ContextInternal)10 VertxInternal (io.vertx.core.impl.VertxInternal)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 AsyncResult (io.vertx.core.AsyncResult)8