Search in sources :

Example 1 with LineEncoder

use of io.netty.handler.codec.string.LineEncoder in project chuidiang-ejemplos by chuidiang.

the class ServerWithNettyHandlers method run.

public void run() throws Exception {
    // (1)
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        // (2)
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(// (3)
        NioServerSocketChannel.class).childHandler(new // (4)
        ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LineBasedFrameDecoder(1000));
                ch.pipeline().addLast(new LineEncoder(Charset.defaultCharset()));
                ch.pipeline().addLast(new StringDecoder(Charset.defaultCharset()));
                ch.pipeline().addLast(serverHandler);
            }
        }).option(ChannelOption.SO_BACKLOG, // (5)
        128).childOption(ChannelOption.SO_KEEPALIVE, // (6)
        true);
        // Bind and start to accept incoming connections.
        // (7)
        ChannelFuture f = b.bind(port).sync();
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LineEncoder(io.netty.handler.codec.string.LineEncoder) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)1 ChannelFuture (io.netty.channel.ChannelFuture)1 EventLoopGroup (io.netty.channel.EventLoopGroup)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)1 LineBasedFrameDecoder (io.netty.handler.codec.LineBasedFrameDecoder)1 LineEncoder (io.netty.handler.codec.string.LineEncoder)1 StringDecoder (io.netty.handler.codec.string.StringDecoder)1