请求报文:前四位(指定报文长度)+报文内容
示例:0010aaooerudyh
1.1、NettyServer类 :启动TCP服务
package com.bokeyuan.socket.server; import com.bokeyuan.socket.BeanUtil; import com.bokeyuan.socket.config.ConfigConstant; import com.bokeyuan.socket.server.codec.MyByteToMessageCodec; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; 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 io.netty.handler.codec.string.StringEncoder; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.net.InetSocketAddress; import java.nio.charset.Charset; /** * @author: chenly * @date: 2021-07-05 10:42 * @description: * @version: 1.0 */ @Component @Slf4j public class NettyServer extends Thread{ @Override public void run() { startServer(); } private void startServer(){ EventLoopGroup bossGroup = null; EventLoopGroup workGroup = null; ServerBootstrap serverBootstrap = null; ChannelFuture future = null; try { //初始化线程组 bossGroup= new NioEventLoopGroup(); workGroup= new NioEventLoopGroup(); //初始化服务端配置 serverBootstrap= new ServerBootstrap(); //绑定线程组 serverBootstrap.group(bossGroup,workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(BeanUtil.getBean(MyByteToMessageCodec.class)); ch.pipeline().addLast(BeanUtil.getBean(MtReadTimeoutHandler.class)); ch.pipeline().addLast(new StringDecoder(Charset.forName(ConfigConstant.MsgCode))); ch.pipeline().addLast(new StringEncoder(Charset.forName(ConfigConstant.MsgCode))); ch.pipeline().addLast(BeanUtil.getBean(NettyServerHandler.class)); } }).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); future = serverBootstrap.bind(new InetSocketAddress(8090)).sync(); log.info(" *************TCP服务端启动成功 Port:{}*********** " , 8090); } catch (Exception e) { log.error("TCP服务端启动异常",e); } finally { if(future!=null){ try { future.channel().closeFuture().sync(); } catch (InterruptedException e) { log.error("channel关闭异常:",e); } } if(bossGroup!=null){ //线程组资源回收 bossGroup.shutdownGracefully(); } if(workGroup!=null){ //线程组资源回收 workGroup.shutdownGracefully(); } } } }