Netty服务类

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();
            }
        }
    }
}

接送端

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;
    }
}

项目启动类添加netty服务器

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();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值