Java Netty Codecs 程序「建议收藏」

服务端定义了一个Handler和三个Decoder。Handler接收客户端的信息,然后传递给decoder过滤处理。1.服务端packagecom.learn.netty.codecs;importio.netty.bootstrap.ServerBootstrap;importio.netty.channel.ChannelFuture;importio.netty.channel.ChannelInitializer;importio.netty.channel.E.

大家好,又见面了,我是你们的朋友全栈君。

服务端定义了一个Handler和三个Decoder。Handler接收客户端的信息,然后传递给decoder过滤处理。

 

1.服务端

package com.learn.netty.codecs;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

public class Server {
    public static void main(String[] args) throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            bootstrap.group(group).channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(8888))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addFirst(new ReadHandler())
                                    .addLast(new FixedLengthDecoder())
                                    .addLast(new LoggingDecoder())
                                    .addLast(new LastDecoder());
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}

 

2.服务端Handler

package com.learn.netty.codecs;

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

public class ReadHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("Received: " + buf.readableBytes());
        ctx.fireChannelRead(buf);
    }
}

 

3.服务端 FixedLengthDecoder

客户端传递的是数字,Java中每个int类型4字节,读取转成字符串,然后传递到下一个Decoder。

package com.learn.netty.codecs;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

public class FixedLengthDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("Fixed: " + byteBuf.readableBytes());
        StringBuilder sb = new StringBuilder();
        while (byteBuf.readableBytes() >= 4) {
            // 读取才能向后传递
            sb.append(byteBuf.readInt());
        }
        list.add(Unpooled.copiedBuffer(sb, CharsetUtil.UTF_8));
    }
}

 

4.服务端 LoggingDecoder

将所有信息记录下来,然后传递接收的数字并追加一个字符串。

package com.learn.netty.codecs;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

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

public class LoggingDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("Logging: " + byteBuf.readableBytes());
        String num = "";
        while (byteBuf.isReadable()) {
            // 读取才能向后传递
            num = byteBuf.readCharSequence(byteBuf.readableBytes(), Charset.defaultCharset()).toString();
            System.out.println(num);
        }
        list.add(Unpooled.copyInt(Integer.parseInt(num)));

        ByteBuf bf = Unpooled.copiedBuffer("Netty", CharsetUtil.UTF_8);
        list.add(bf);
    }
}

 

5.服务端 LastDecoder

读取接收的数字和字符串。

package com.learn.netty.codecs;

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

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

public class LastDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        // Decoder没有读取会被调用多次
        // System.out.println("Last readable: " + byteBuf.readableBytes());
        // System.out.println(byteBuf.toString(Charset.defaultCharset()));

        System.out.println("Last readable: " + byteBuf.readableBytes());
        if (byteBuf.readableBytes() == 4) {
            int num = byteBuf.readInt();
            System.out.println("num: " + num);
        } else {
            ByteBuf buf = byteBuf.readBytes(byteBuf.readableBytes());
            System.out.println(buf.toString(Charset.defaultCharset()));
        }
    }
}

 

6.客户端

向服务端传递 6 个 int。

package com.learn.netty.codecs;


import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;

import java.net.InetSocketAddress;

public class Client {
    public static void main(String[] args) throws Exception {
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            System.out.println("client active");
                            ctx.writeAndFlush(Unpooled.copyInt(1));
                            ctx.writeAndFlush(Unpooled.copyInt(2));
                            ctx.writeAndFlush(Unpooled.copyInt(3));
                            ctx.writeAndFlush(Unpooled.copyInt(4));
                            ctx.writeAndFlush(Unpooled.copyInt(5));
                            ctx.writeAndFlush(Unpooled.copyInt(6));
                        }
                    });
                }
            }).remoteAddress(new InetSocketAddress("127.0.0.1", 8888));
            ChannelFuture future = bootstrap.connect().sync();
            future.channel().close().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}

 

结果:

Received: 24
Fixed: 24
Logging: 6
123456
Last readable: 4
num: 123456
Last readable: 5
Netty

 

原文地址: https://www.zhblog.net/go/java/tutorial/java-netty-codecs?t=597

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/128663.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 如何使用ABAP代码反序列化JSON字符串成ABAP结构「建议收藏」

    如何使用ABAP代码反序列化JSON字符串成ABAP结构「建议收藏」如何使用ABAP代码反序列化JSON字符串成ABAP结构

    2022年4月21日
    37
  • PHP安装包TS和NTS的区别-Centos7 LANMP环境搭建(最完善版本)

    PHP安装包TS和NTS的区别-Centos7 LANMP环境搭建(最完善版本)

    2022年2月17日
    49
  • windows 7 旗舰版下,安装vs2010旗舰版终于成功!

    windows 7 旗舰版下,安装vs2010旗舰版终于成功!折腾了好久好久郁闷了好久着急了好久终于把VS2010旗舰版安装成功了!情况:1.我的本本是tinkpad,购买的时候预装了window7homebasic在网上找了一下序列号升级到window7旗舰版本。2.之前我一直用windowsxp对window7相当的陌生!直接跳级可不是简单的事情啊!!(因为我不熟徐windown7安装失败了好几次!)3.在我安装vs20…

    2022年7月20日
    22
  • 微信小程序自定义组件

    微信小程序自定义组件

    2021年6月11日
    138
  • 【C#】list 去重(转载)

    【C#】list 去重(转载)一、查阅文档Enumerable.Distinct方法是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组、集合中的重复元素,还可以自定义去重的规则。有两个重载方法:////摘要://通过使用默认的相等比较器对值进行比较返回序列中的非重复元素。////参数://source://要从中移除重复元素的序列。.

    2022年5月25日
    70
  • js手机号正则校验_正则表达式验证手机号码格式

    js手机号正则校验_正则表达式验证手机号码格式这篇文章主要介绍了2022手机号码JS正则表达式验证实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下​概念正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。简介正则表达式是对字符串(包括普通字符(例如,a到z之间的字母)和特殊字符(称为“元字符”))操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字

    2022年9月15日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号