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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 版本号命名规范[通俗易懂]

    版本号命名规范[通俗易懂]写在前面:本文章旨在总结备份、方便以后查询,由于是个人总结,如有不对,欢迎指正;另外,内容大部分来自网络、书籍、和各类手册,如若侵权请告知,马上删帖致歉。原文:http://wsfdl.com/devops/2016/09/27/%E7%89%88%E6%9C%AC%E5%8F%B7.html#首先看看某些常见软件的版本号:LinuxKernel:0.0.1,1.0.0,2.6.32,3.0.18…,若用X.Y.Z表示,则偶数Y表示稳定版本,奇数Y表示开发版本。Windo

    2022年9月11日
  • APACHE 服务器开启URL REWRITE模块的方法

    APACHE 服务器开启URL REWRITE模块的方法

    2021年9月18日
  • XPS文件怎么打开?可以转成PDF格式吗?

    XPS文件怎么打开?可以转成PDF格式吗?我们在打印文件时经常会遇到和我们保存的格式不一样的情况,为了无法轻易变更档案中的数据,有些朋友就将其保存为xps格式文件。下面就一起来看一下打开xps格式文件和转成PDF的方法。1、如何打开XPS文件目前很多人的电脑系统已更新的WIN10系统,其实win10是自带打开XPS文件功能软件的,操作也很方便。首先点击电脑左下角的开始菜单,在搜索框中输入XPSViewer,并点击运行软件。接着在主界面中选择要打开的文件,即可进行阅读操作。2、如何将XPS转成PDF我们可以使用一些在线转换工具,这样不

    2022年6月4日
  • python py2exe_编写简单网页

    python py2exe_编写简单网页简介py2exe是 Python Distutils 的一个外部扩展,它可以把Python脚本转为可执行的Windows程序,无需安装Python即可运行.你可以在主页 SourceForge 得到更多资源. 说明py2exe可以把Python程序转为包,能够在其他没有安装Python 的电脑上运行。Pythonisneede

    2022年9月4日
  • html中table样式_html中table的用法

    html中table样式_html中table的用法转自:http://atgoingguoat.iteye.com/blog/2074431常用table样式,备自己常年复制用。 效果图   Java代码  “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml

    2022年9月20日
  • 命名规范与规则

    命名规范与规则命名规范1、项目名全部小写,就是如果项目名是多个英语单词组成的,每个单词都要全部小写。如:doubanssm。2、包名全部小写。3、类名首字母大写,若类名由多个单词构成,每个单词首字母大写,即

    2022年7月1日

发表回复

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

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