Clase de servicio Netty

Monitoreo del servidor Netty

package com.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.PreDestroy;

/**
 * @Description 服务端监听
 */
@Slf4j
@Component
public class NettyServerListener {
    
    
    /**
     * netty启动端口号
     */
    private static int port = 8081;

    //接受客户端连接的请求
    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    //处理客户端的读写操作
    NioEventLoopGroup workGroup = new NioEventLoopGroup();

    /**
     * 关闭服务
     */
    @PreDestroy
    public void close() {
    
    
        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    /**
     * 启动
     */
    public void start() {
    
    
        /**
         *  客户端创建两个线程池组分别为:boss线程组和工作线程组
         */
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
    
    
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
    
    
                        socketChannel.pipeline().addLast(new ServerHandler());
                        // 解决拆包问题
                        socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        // 获取数据的结果为string类型
                        socketChannel.pipeline().addLast(new StringEncoder());
                        socketChannel.pipeline().addLast(new ServerHandler());
                    }
                });
        try {
    
    
            // 绑定端口号,同步等待成功
            ChannelFuture future = serverBootstrap.bind(port).sync();
            log.info("Netty通讯服务启动成功:{}",port);
            // 等待服务器监听端口
            future.channel().closeFuture().sync();
        } catch (Exception e) {
    
    
            log.warn("Netty通讯服务启动失败:{}" , port);
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                // 释放线程池资源
                bossGroup.shutdownGracefully().sync();
                workGroup.shutdownGracefully().sync();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

Terminal de recogida

package com.demo.netty;

import com.demo.service.DemoService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    
    
	//调用Service层
    @Autowired
    private DemoService demoService;
    //保存通道
	public static Map list = new ConcurrentHashMap();
	
    public static ServerHandler serverHandler;
    
    public ServerHandler() {
    
    
    }
    @PostConstruct
    public void init() {
    
    
        serverHandler = this; //new ServerHandler();
        serverHandler.demoService = this.demoService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
    
    
        //log.info("--:" + (SocketChannel) channelHandlerContext.channel());
        String request = byteBuf.toString(CharsetUtil.UTF_8);
        log.info("通讯连接:{}", request);
        boolean containsCN = request.contains("CN=20");
        if (containsCN) {
    
    
        	//保存通道
        	list.put(mac, (SocketChannel) channelHandlerContext.channel());
            int code = -1;
            String CN2 = request.split("CN=")[1].split(";", 0)[0];
            if ("2011".equals(CN2)) {
    
    
                code = serverHandler.demoService.insertData(request);
            }
			channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer("CN=" + CN2+";code=" + code, CharsetUtil.UTF_8));
        }
    }

	/**
     * 往硬件发送数据通讯接口
     * @param data 数据
     * @param mac 通道MAC
     * @return
     */
    public static String sendmsg(String mac,String data) {
    
    
        if (StringUtils.isEmpty(list.get(mac))) {
    
    
            return "通道不存在!";
        }
        Channel c = (Channel) list.get(mac);
        log.info("sendmsg-getMac:{}", list.get(mac));
        c.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
        return returnText;
    }
}

Agregue el servidor netty a la clase de inicio del proyecto

public class DemoApplication implements CommandLineRunner {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(DemoApplication.class, args);
        SpringApplication springApplication = new SpringApplication(DemoApplication.class);
        springApplication.run(args);
    }
    @Override
    public void run(String... args) {
    
    
        new NettyServerListener().start();
    }

Supongo que te gusta

Origin blog.csdn.net/qq_42476834/article/details/113117637
Recomendado
Clasificación