Example usage for io.netty.handler.codec.bytes ByteArrayEncoder ByteArrayEncoder

List of usage examples for io.netty.handler.codec.bytes ByteArrayEncoder ByteArrayEncoder

Introduction

In this page you can find the example usage for io.netty.handler.codec.bytes ByteArrayEncoder ByteArrayEncoder.

Prototype

ByteArrayEncoder

Source Link

Usage

From source file:com.nus.mazegame.client.GameClient.java

public static void init(String host, final int port, final String type, SocketAddress localAddr)
        throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override//from   ww w  .j  a v  a  2  s . co  m
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            // Decoders
            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
            p.addLast("bytesDecoder", new ByteArrayDecoder());

            // Encoder
            p.addLast("frameEncoder", new LengthFieldPrepender(4));
            p.addLast("bytesEncoder", new ByteArrayEncoder());
            p.addLast(GameClientHandler.instance);
            GameInfo.instance.setType(type);
            GameInfo.instance.setHostPort(port);
        }
    });

    // Make the connection attempt.
    SocketAddress address = new InetSocketAddress(host, port);
    ChannelFuture f;
    if (localAddr == null)
        f = b.connect(address).sync();
    else
        f = b.connect(address, localAddr).sync();

    // Wait until the connection is closed.
    f.channel().closeFuture().sync();
}

From source file:com.nus.mazegame.server.GameServer.java

public static void init(int port, int x, int y, int treasure, boolean isSlave) throws Exception {
    GameService.gameService = new GameService(x, y, treasure, isSlave);

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from www  .j a v a2  s. co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        // Decoders
                        p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                        p.addLast("bytesDecoder", new ByteArrayDecoder());

                        // Encoder
                        p.addLast("frameEncoder", new LengthFieldPrepender(4));
                        p.addLast("bytesEncoder", new ByteArrayEncoder());
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new GameServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();
        Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO, "Server started...");
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.qualys.jserf.SerfClientInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();

    if (log.isDebugEnabled()) {
        pipeline.addFirst("loggingHandler", new LoggingHandler());
    }// w w w. j av a2s.  c  o m

    pipeline.addLast("reconnectHandler", new ReconnectClientHandler(channelManger));

    log.debug("Adding ByteArray Encoder");
    pipeline.addLast("bytesEncoder", new ByteArrayEncoder());

    log.debug("Adding SerfClientHandler");
    pipeline.addLast("handler", new SerfClientHandler(extractorManager, messagePack, callBacksBySequence));
}

From source file:net.kuujo.copycat.netty.NettyTcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> connect() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        future.complete(null);//  w w  w  . jav a 2  s.  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;
    }

    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(), host, port));
            }
            pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
            pipeline.addLast("bytesDecoder", new ByteArrayDecoder());
            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
            pipeline.addLast("bytesEncoder", new ByteArrayEncoder());
            pipeline.addLast("handler", channelHandler);
        }
    });

    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, true);
    bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout());

    bootstrap.connect(host, port).addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            channel = channelFuture.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(channelFuture.cause());
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.NettyTcpProtocolServer.java

License:Apache License

@Override
public synchronized CompletableFuture<Void> listen() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {/*from  ww  w.ja  v  a  2 s  .  c  o m*/
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    serverGroup = new NioEventLoopGroup();
    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("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                    pipeline.addLast("bytesDecoder", new ByteArrayDecoder());
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("bytesEncoder", new ByteArrayEncoder());
                    pipeline.addLast("handler", new ServerHandler());
                }
            }).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, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    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(host, port).addListener((ChannelFutureListener) channelFuture -> {
        channelFuture.channel().closeFuture().addListener(closeFuture -> {
            workerGroup.shutdownGracefully();
        });

        if (channelFuture.isSuccess()) {
            channel = channelFuture.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(channelFuture.cause());
        }
    });
    return future;
}

From source file:org.aotorrent.client.InboundChannelInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();/*from   w  w w  .j  a  v  a2 s. co  m*/
    //p.addLast(new LoggingHandler(LogLevel.INFO));
    p.addLast("timeoutHandler", new ReadTimeoutHandler(60, TimeUnit.SECONDS));
    p.addLast("bytesEncoder", new ByteArrayEncoder());
    p.addLast("handshakeHandler", new InboundHandshakeHandler(client));
    p.addLast("lengthFrameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 4));
    p.addLast("peerRequestDecoder", new PeerRequestDecoder());
}

From source file:org.aotorrent.client.OutboundChannelInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();/* w ww . j  a  va  2 s  .c  om*/
    //p.addLast(new LoggingHandler(LogLevel.INFO));
    p.addLast("trafficCounter", torrentEngine.getCounter());
    p.addLast("timeoutHandler", new ReadTimeoutHandler(60, TimeUnit.SECONDS));
    p.addLast("bytesEncoder", new ByteArrayEncoder());
    p.addLast("handshakeHandler", new OutboundHandshakeHandler(torrentEngine));
    p.addLast("lengthFrameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 4));
    p.addLast("peerRequestDecoder", new PeerRequestDecoder());
}

From source file:org.apache.reef.wake.remote.transport.netty.NettyChannelInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAXFRAMELENGTH, 0, 4, 0, 4))
            .addLast("bytesDecoder", new ByteArrayDecoder())
            .addLast("frameEncoder", new LengthFieldPrepender(4))
            .addLast("bytesEncoder", new ByteArrayEncoder()).addLast("chunker", new ChunkedReadWriteHandler())
            .addLast("handler", handlerFactory.createChannelInboundHandler());
}

From source file:org.kaaproject.kaa.server.transports.tcp.transport.netty.AbstractKaaTcpServerInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    final ChannelPipeline p = ch.pipeline();

    final UUID uuid = UUID.randomUUID();

    LOG.debug("KaaTcpServerInitializer Initializing Channel {} connection from {}:{}", uuid,
            ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort());

    Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY);
    uuidAttr.set(uuid);/*from  w  ww  .  jav a2s  .  c o  m*/

    p.addLast("binaryDecoder", new ByteArrayDecoder());
    p.addLast("kaaTcpDecoder", getDecoder());
    p.addLast("binaryEncoder", new ByteArrayEncoder());
    p.addLast("kaaTcpEncoder", new KaaTcpEncoder());
    p.addLast("mainHandler", getMainHandler(uuid));
    p.addLast("kaaTcpExceptionHandler", new KaaTcpExceptionHandler());
}

From source file:org.opendaylight.sxp.core.handler.HandlerFactory.java

License:Open Source License

/**
 * @return Gets all encoders/*from   w w w.  j a v a 2  s. c  om*/
 */
public synchronized ChannelHandler[] getEncoders() {
    encoders.addFirst(new ByteArrayEncoder());
    ChannelHandler[] out = encoders.toArray(new ChannelHandler[encoders.size()]);
    encoders.pollFirst();
    return out;
}