Example usage for io.netty.handler.codec.string StringEncoder StringEncoder

List of usage examples for io.netty.handler.codec.string StringEncoder StringEncoder

Introduction

In this page you can find the example usage for io.netty.handler.codec.string StringEncoder StringEncoder.

Prototype

public StringEncoder(Charset charset) 

Source Link

Document

Creates a new instance with the specified character set.

Usage

From source file:be.yildizgames.module.network.netty.NettyChannelInitializer.java

License:MIT License

@Override
protected void initChannel(final SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    switch (factory.getCodec()) {
    case STRING://from  w w  w.  ja  v  a  2 s  . co m
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        break;
    case HTTP:
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new ChunkedWriteHandler());
        break;
    case WEBSOCKET:
        if (this.factory.isServer()) {
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast(new HttpObjectAggregator(65536));
            pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));
        } else {
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(8192));
        }
        break;
    default:
        throw new IllegalArgumentException("Unknown codec: " + factory.getCodec());
    }
    pipeline.addLast("handler", this.factory.create());
}

From source file:books.netty.protocol.file.FileServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from   w  ww.ja v  a  2  s  . c o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    /*
                     * (non-Javadoc)
                     *
                     * @see
                     * io.netty.channel.ChannelInitializer#initChannel(io
                     * .netty.channel.Channel)
                     */
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8),
                                new FileServerHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        System.out.println("Start file server at port : " + port);
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:chat.viska.xmpp.NettyTcpSession.java

License:Apache License

@SchedulerSupport(SchedulerSupport.CUSTOM)
@Override//from www  . j av  a2 s .com
protected Completable openConnection(final Compression connectionCompression,
        final Compression tlsCompression) {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(nettyEventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel channel) throws SSLException {
            if (getConnection().getTlsMethod() == Connection.TlsMethod.DIRECT) {
                tlsHandler = TLS_CONTEXT_BUILDER.build().newHandler(channel.alloc());
                channel.pipeline().addLast(PIPE_TLS, tlsHandler);
            } else {
                channel.pipeline().addLast(PIPE_TLS, new ChannelDuplexHandler());
            }
            channel.pipeline().addLast(PIPE_COMPRESSOR, new ChannelDuplexHandler());
            channel.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_STANZA_SIZE_BYTE, false, false,
                    Unpooled.wrappedBuffer(">".getBytes(StandardCharsets.UTF_8))));
            channel.pipeline().addLast(new StreamClosingDetector());
            channel.pipeline().addLast(PIPE_DECODER_XML, new XmlDecoder());
            channel.pipeline().addLast(new SimpleChannelInboundHandler<XmlDocumentStart>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final XmlDocumentStart msg)
                        throws Exception {
                    if (!"UTF-8".equalsIgnoreCase(msg.encoding())) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.UNSUPPORTED_ENCODING,
                                "Only UTF-8 is supported in XMPP stream."));
                    }
                }
            });
            channel.pipeline().addLast(new StreamOpeningDetector());
            channel.pipeline().addLast(new XmlFrameDecoder(MAX_STANZA_SIZE_BYTE));
            channel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final String msg)
                        throws Exception {
                    try {
                        feedXmlPipeline(preprocessInboundXml(msg));
                    } catch (SAXException ex) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.BAD_FORMAT));
                    }
                }
            });
            channel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
                }

                @Override
                public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
                    if (cause instanceof Exception) {
                        triggerEvent(new ExceptionCaughtEvent(NettyTcpSession.this, (Exception) cause));
                    } else {
                        throw new RuntimeException(cause);
                    }
                }
            });
        }
    });

    final ChannelFuture channelFuture = bootstrap.connect(getConnection().getDomain(),
            getConnection().getPort());
    return Completable.fromFuture(channelFuture).andThen(Completable.fromAction(() -> {
        this.nettyChannel = (SocketChannel) channelFuture.channel();
        nettyChannel.closeFuture().addListener(it -> changeStateToDisconnected());
    }));
}

From source file:com.alibaba.dubbo.qos.server.handler.QosProcessHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;/* www  . j av  a 2 s.c  o  m*/
    }

    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());

    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}

From source file:com.baoxue.netty.file.FileServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w ww .  j  av a 2  s .  c o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    /*
                     * (non-Javadoc)
                     * 
                     * @see
                     * io.netty.channel.ChannelInitializer#initChannel(io
                     * .netty.channel.Channel)
                     */
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8),
                                new FileServerHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        System.out.println("Start file server at port : " + port);
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.cat.netty.file.FileServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*ww  w .  j  a  v  a 2  s. co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    /*
                     * (non-Javadoc)
                     *
                     * @see
                     * io.netty.channel.ChannelInitializer#initChannel(io
                     * .netty.channel.Channel)
                     */
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8),
                                new FileServerHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        System.out.println("Server start at port : " + port);
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.doctor.netty5.example.chatroom.ChatRoomClient.java

License:Apache License

public void start() throws InterruptedException {
    NioEventLoopGroup workersGroup = new NioEventLoopGroup(1);

    try {//from  ww  w .ja va 2 s .c  om
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workersGroup).channel(NioSocketChannel.class).remoteAddress(host, port)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new DelimiterBasedFrameDecoder(8049, true, Delimiters.lineDelimiter()));
                        ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new ChatRoomClientHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.connect().sync();
        channelFuture.channel().closeFuture().sync();

    } finally {
        workersGroup.shutdownGracefully();
    }
}

From source file:com.doctor.netty5.example.chatroom.ChatRoomServer.java

License:Apache License

public void start() throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap();
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*ww  w . j a v a  2 s .  c o m*/
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new DelimiterBasedFrameDecoder(8049, true, Delimiters.lineDelimiter()));
                        ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new ChatRoomServerHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind().sync();
        System.out.println(ChatRoomServer.class.getName() + " started and listen on port:"
                + channelFuture.channel().localAddress());

        channelFuture.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.doctor.netty5.example.echo.EchoClient.java

License:Apache License

public void start() throws InterruptedException {
    NioEventLoopGroup workersGroup = new NioEventLoopGroup(1);

    try {//from  ww  w  .  java2s .  c o  m
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workersGroup).channel(NioSocketChannel.class).remoteAddress(host, port)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(2048));
                        ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.connect().sync();
        channelFuture.channel().closeFuture().sync();

    } finally {
        workersGroup.shutdownGracefully();
    }
}

From source file:com.doctor.netty5.example.echo.EchoServer.java

License:Apache License

public void start() throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap();
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {// w  w w  .  j av a  2 s.c  o m
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(2048));
                        ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on port:"
                + channelFuture.channel().localAddress());

        channelFuture.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}