Netty中ChannelInitializer的使用

本文详细介绍了在Netty框架中,ChannelInitializer组件的作用及其使用场合。它主要用于客户端和服务端之间的消息处理,通过设置编码和解码格式,确保特殊字符的正确传输。在客户端和服务端实现中,通过继承ChannelInitializer并重写initChannel方法,可以定制化处理流程。

在Netty客户端和服务端我们都会使用到ChannelInitializer进行消息的处理,那么ChannelInitializer的作用和使用场合以及如何使用下文将会介绍。

ChannelInitializer的作用:用来进行设置出站解码器和入站编码器。

使用场合:客户端和服务端之间消息的传递包含特殊字符需要统一编码格式时,在客户端和服务端加上ChannelInitializer继承类,重写initChannel方法,设置编码和解码格式。但当传输的数据不包含特殊字符例如报文时,客户端和服务端不需要写ChannelInitializer继承类

代码举例
客户端:

package client;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline p = channel.pipeline();
        p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new ClientHandler());
    }
}

服务端:

package com.safelocate.app.nettyServer;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        channel.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast(new ServerHandler());
    }
}

https://www.cnblogs.com/myitnews/p/12213602.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值