netty: ByteToMessageCodec的用法

本文介绍了如何在Java中创建一个自定义的ByteToMessageCodec子类,重写encode和decode方法,以及如何编写一个简单的ChannelInboundHandlerAdapter。并在NettyTCP服务器中集成这两个处理程序,以处理和解码数据包。
摘要由CSDN通过智能技术生成

一、创建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<String> {
    @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<Object> 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<SocketChannel>() {
                @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();
        }



    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值