Netty中ChannelInitializer的使用

在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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个简单的 Spring Boot 使用 Netty 的示例: 1. 首先,添加以下依赖到 pom.xml 文件: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.48.Final</version> </dependency> ``` 2. 创建一个 Netty 服务器类,并实现 ChannelInboundHandlerAdapter 接口: ```java @Component @ChannelHandler.Sharable public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 处理客户端请求 ByteBuf byteBuf = (ByteBuf) msg; byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes); String request = new String(bytes, "UTF-8"); System.out.println("收到客户端请求:" + request); // 响应客户端请求 String response = "Hello, " + request; ByteBuf responseBuf = Unpooled.copiedBuffer(response.getBytes()); ctx.write(responseBuf); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 3. 创建 Netty 服务器启动类,并使用 @PostConstruct 注解启动 Netty 服务器: ```java @Component public class NettyServer { private final NettyServerHandler nettyServerHandler; @Autowired public NettyServer(NettyServerHandler nettyServerHandler) { this.nettyServerHandler = nettyServerHandler; } @PostConstruct public void start() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(nettyServerHandler); } }); ChannelFuture future = serverBootstrap.bind(8080).sync(); if (future.isSuccess()) { System.out.println("Netty 服务器启动成功"); } } } ``` 以上示例,我们创建了一个 Netty 服务器,监听 8080 端口。当客户端连接到服务器时,服务器会收到客户端请求,并响应客户端请求。 注意:如果你的 Spring Boot 应用部署在 Tomcat 或者 Jetty 容器,则需要在启动方法上添加 @Bean 注解,以确保正确启动 Netty 服务器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值