netty: ByteToMessageCodec的用法

一、创建ByteToMessageCodec的子类并重写encode和decode方法

package cn.edu.tju;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.nio.charset.Charset;
import java.util.List;

public class MyByteToMessageCodec extends ByteToMessageCodec {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf byteBuf) throws Exception {
        System.out.println("encode was called......");
        String finalString = "server response: " + s;
        byteBuf.writeBytes(finalString.getBytes());
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception {
        System.out.println("decode was called......");

        int length = byteBuf.readableBytes();
        byte[] bytes = new byte[length];

        byteBuf.readBytes(bytes);
        String str = new String (bytes);
        list.add(str);
        System.out.println("codec received message: " + str);



    }
}

 
  

二、编写一个简单的ChannelInboundHandlerAdapter

package cn.edu.tju;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MySimpleHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String str = (String)msg;
        System.out.println("handler received message: " + msg);
        ctx.channel().writeAndFlush(str.toUpperCase());
    }
}

三、编写netty TCP服务器,并在ChannelPipeline中加入上述两个handler

package cn.edu.tju;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

public class NettyTcpServer10 {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(16);

        try {
            ServerBootstrap  serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);



            serverBootstrap.childHandler(new ChannelInitializer() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new MyByteToMessageCodec());
                    pipeline.addLast(new MySimpleHandler());

                }
            });

            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(8899))
                    .sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex){
            System.out.println(ex.getMessage());
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }



    }
}

你可能感兴趣的:(Netty,python,windows,开发语言)