Search in sources :

Example 81 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project baseio by generallycloud.

the class NettyClientThread method main.

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
        b.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new HelloClient());
            }
        });
        System.out.println("################## Test start ####################");
        ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
        System.out.println(f.isSuccess());
        Channel channel = f.channel();
        System.out.println("channel is active :" + channel.isActive() + ",channel:" + channel);
        int len = 1024 * 64;
        StringBuilder s = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            s.append(len % 10);
        }
        final String msg = s.toString();
        ThreadUtil.execute(new Runnable() {

            @Override
            public void run() {
                int i = 0;
                for (; ; ) {
                    // String s = "hello Service! ---> :" + i;
                    ChannelFuture f = channel.writeAndFlush(msg);
                    ThreadUtil.sleep(1);
                    System.out.println(f.isDone() + "--------" + i);
                    i++;
                }
            }
        });
        ThreadUtil.sleep(Integer.MAX_VALUE);
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 82 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project reactor-netty by reactor.

the class ReactorNetty method addHandlerBeforeReactorEndHandlers.

/**
 * A common implementation for the {@link NettyContext#addHandlerLast(String, ChannelHandler)}
 * method that can be reused by other implementors.
 * <p>
 * This implementation will look for reactor added handlers on the right hand side of
 * the pipeline, provided they are identified with the {@link NettyPipeline#RIGHT}
 * prefix, and add the handler just before the first of these.
 *
 * @param context the {@link NettyContext} on which to add the decoder.
 * @param name the name of the decoder.
 * @param handler the decoder to add before the final reactor-specific handlers.
 * @see NettyContext#addHandlerLast(String, ChannelHandler).
 */
static void addHandlerBeforeReactorEndHandlers(NettyContext context, String name, ChannelHandler handler) {
    Objects.requireNonNull(name, "name");
    Objects.requireNonNull(handler, "handler");
    Channel channel = context.channel();
    boolean exists = channel.pipeline().get(name) != null;
    if (exists) {
        if (log.isDebugEnabled()) {
            log.debug("Handler [{}] already exists in the pipeline, decoder has been skipped", name);
        }
        return;
    }
    // we need to find the correct position
    String before = null;
    for (String s : channel.pipeline().names()) {
        if (s.startsWith(NettyPipeline.RIGHT)) {
            before = s;
            break;
        }
    }
    if (before == null) {
        channel.pipeline().addLast(name, handler);
    } else {
        channel.pipeline().addBefore(NettyPipeline.ReactiveBridge, name, handler);
    }
    registerForClose(shouldCleanupOnClose(channel), name, context);
    if (log.isDebugEnabled()) {
        log.debug("Added decoder [{}] at the end of the user pipeline, full pipeline: {}", name, channel.pipeline().names());
    }
}
Also used : Channel(io.netty.channel.Channel)

Example 83 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project atomix by atomix.

the class NettyMessagingService method openChannel.

private CompletableFuture<Channel> openChannel(Endpoint ep) {
    Bootstrap bootstrap = bootstrapClient(ep);
    CompletableFuture<Channel> retFuture = new CompletableFuture<>();
    ChannelFuture f = bootstrap.connect();
    f.addListener(future -> {
        if (future.isSuccess()) {
            retFuture.complete(f.channel());
        } else {
            retFuture.completeExceptionally(future.cause());
        }
    });
    log.debug("Established a new connection to {}", ep);
    return retFuture;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) CompletableFuture(java.util.concurrent.CompletableFuture) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 84 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project CloudNet by Dytanic.

the class PacketInAuthHandler method handleAuth.

@Override
public void handleAuth(Auth auth, AuthType authType, Document authData, PacketSender packetSender) {
    if (!(packetSender instanceof CloudNetClientAuth))
        return;
    CloudNetClientAuth client = (CloudNetClientAuth) packetSender;
    switch(authType) {
        case CLOUD_NET:
            {
                String key = authData.getString("key");
                String id = authData.getString("id");
                if (CloudNet.getInstance().getWrappers().containsKey(id)) {
                    Wrapper cn = CloudNet.getInstance().getWrappers().get(id);
                    String wrapperKey = CloudNet.getInstance().getConfig().getWrapperKey();
                    if (wrapperKey != null && cn.getChannel() == null && wrapperKey.equals(key)) {
                        Channel channel = client.getChannel();
                        channel.pipeline().remove("client");
                        client.getChannel().writeAndFlush(new PacketOutAuthResult(new AuthLoginResult(true))).syncUninterruptibly();
                        channel.pipeline().addLast(new CloudNetClient(cn, channel));
                        return;
                    } else {
                        client.getChannel().writeAndFlush(new PacketOutAuthResult(new AuthLoginResult(false))).syncUninterruptibly();
                        CloudNet.getLogger().info("Authentication failed [" + (wrapperKey != null ? "Invalid WrapperKey or Wrapper is already connected!" : "WrapperKey not found, please copy a wrapper key to this instance") + "]");
                    }
                } else {
                    client.getChannel().writeAndFlush(new PacketOutAuthResult(new AuthLoginResult(false))).syncUninterruptibly();
                }
            }
            return;
        case GAMESERVER_OR_BUNGEE:
            {
                ServiceId serviceId = authData.getObject("serviceId", ServiceId.class);
                if (CloudNet.getInstance().getWrappers().containsKey(serviceId.getWrapperId())) {
                    Wrapper wrapper = CloudNet.getInstance().getWrappers().get(serviceId.getWrapperId());
                    if (wrapper.getServers().containsKey(serviceId.getServerId())) {
                        MinecraftServer minecraftServer = wrapper.getServers().get(serviceId.getServerId());
                        if (minecraftServer.getChannel() == null && minecraftServer.getServerInfo().getServiceId().getUniqueId().equals(serviceId.getUniqueId())) {
                            Channel channel = client.getChannel();
                            channel.pipeline().remove("client");
                            channel.pipeline().addLast(new CloudNetClient(minecraftServer, channel));
                            return;
                        }
                    } else if (wrapper.getCloudServers().containsKey(serviceId.getServerId())) {
                        CloudServer minecraftServer = wrapper.getCloudServers().get(serviceId.getServerId());
                        if (minecraftServer.getChannel() == null && minecraftServer.getServerInfo().getServiceId().getUniqueId().equals(serviceId.getUniqueId())) {
                            Channel channel = client.getChannel();
                            channel.pipeline().remove("client");
                            channel.pipeline().addLast(new CloudNetClient(minecraftServer, channel));
                            return;
                        }
                    } else if (wrapper.getProxys().containsKey(serviceId.getServerId())) {
                        ProxyServer minecraftServer = wrapper.getProxys().get(serviceId.getServerId());
                        if (minecraftServer.getChannel() == null && minecraftServer.getProxyInfo().getServiceId().getUniqueId().equals(serviceId.getUniqueId())) {
                            Channel channel = client.getChannel();
                            channel.pipeline().remove("client");
                            channel.pipeline().addLast(new CloudNetClient(minecraftServer, channel));
                            return;
                        }
                    } else {
                        client.getChannel().close().syncUninterruptibly();
                    }
                } else {
                    client.getChannel().close().syncUninterruptibly();
                }
            }
            return;
        default:
            return;
    }
}
Also used : AuthLoginResult(de.dytanic.cloudnet.lib.network.auth.AuthLoginResult) Wrapper(de.dytanic.cloudnetcore.network.components.Wrapper) PacketOutAuthResult(de.dytanic.cloudnet.lib.network.auth.packetio.PacketOutAuthResult) Channel(io.netty.channel.Channel) CloudNetClientAuth(de.dytanic.cloudnetcore.network.CloudNetClientAuth) CloudNetClient(de.dytanic.cloudnetcore.network.CloudNetClient) CloudServer(de.dytanic.cloudnetcore.network.components.CloudServer) ServiceId(de.dytanic.cloudnet.lib.service.ServiceId) MinecraftServer(de.dytanic.cloudnetcore.network.components.MinecraftServer) ProxyServer(de.dytanic.cloudnetcore.network.components.ProxyServer)

Example 85 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project herddb by diennea.

the class NettyConnector method connect.

public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout, ChannelEventListener receiver, final ExecutorService callbackExecutor, final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup) throws IOException {
    try {
        final SslContext sslCtx = !ssl ? null : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        Class<? extends Channel> channelType;
        InetSocketAddress inet = new InetSocketAddress(host, port);
        SocketAddress address;
        String hostAddress = NetworkUtils.getAddress(inet);
        MultithreadEventLoopGroup group;
        if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) {
            channelType = LocalChannel.class;
            address = new LocalAddress(hostAddress + ":" + port + ":" + ssl);
            group = localEventsGroup;
        } else {
            channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class;
            address = inet;
            group = networkGroup;
        }
        Bootstrap b = new Bootstrap();
        AtomicReference<NettyChannel> result = new AtomicReference<>();
        b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout).handler(new ChannelInitializer<Channel>() {

            @Override
            public void initChannel(Channel ch) throws Exception {
                NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
                result.set(channel);
                channel.setMessagesReceiver(receiver);
                if (ssl) {
                    ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                if (socketTimeout > 0) {
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout));
                }
                ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                // 
                ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                ch.pipeline().addLast(new InboundMessageHandler(channel));
            }
        });
        LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}", new Object[] { host, port, ssl, address });
        b.connect(address).sync();
        return result.get();
    } catch (InterruptedException ex) {
        throw new IOException(ex);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) MultithreadEventLoopGroup(io.netty.channel.MultithreadEventLoopGroup) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) LocalAddress(io.netty.channel.local.LocalAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Aggregations

Channel (io.netty.channel.Channel)889 Test (org.junit.Test)242 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)227 ChannelFuture (io.netty.channel.ChannelFuture)204 Bootstrap (io.netty.bootstrap.Bootstrap)201 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)193 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)176 InetSocketAddress (java.net.InetSocketAddress)169 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)152 IOException (java.io.IOException)143 EventLoopGroup (io.netty.channel.EventLoopGroup)142 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)138 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)131 ByteBuf (io.netty.buffer.ByteBuf)112 SocketChannel (io.netty.channel.socket.SocketChannel)105 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)99 ChannelPipeline (io.netty.channel.ChannelPipeline)98 CountDownLatch (java.util.concurrent.CountDownLatch)97 LocalChannel (io.netty.channel.local.LocalChannel)93 LocalServerChannel (io.netty.channel.local.LocalServerChannel)88