liuyongxin преди 1 година
ревизия
9c62a633d3

+ 33 - 0
.gitignore

@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/

+ 109 - 0
pom.xml

@@ -0,0 +1,109 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>com.lutao</groupId>
+    <artifactId>TcpServer</artifactId>
+    <version>1.0.0</version>
+    <name>TcpServer</name>
+    <description>TcpServer</description>
+    <properties>
+        <java.version>1.8</java.version>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+        <spring-boot.version>2.7.5</spring-boot.version>
+    </properties>
+    <dependencies>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <version>1.18.30</version>
+        </dependency>
+
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <version>5.3.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.google.code.gson</groupId>
+            <artifactId>gson</artifactId>
+            <version>2.8.6</version> <!-- 确保检查最新版本 -->
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.75</version> <!-- 请检查并使用最新版本 -->
+        </dependency>
+
+
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty-all</artifactId>
+            <version>4.1.68.Final</version> <!-- 使用最新版本 -->
+        </dependency>
+
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-dependencies</artifactId>
+                <version>${spring-boot.version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>3.8.1</version>
+                <configuration>
+                    <source>1.8</source>
+                    <target>1.8</target>
+                    <encoding>UTF-8</encoding>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>${spring-boot.version}</version>
+                <configuration>
+                    <mainClass>com.lutao.tcp.server.TcpServerApplication</mainClass>
+                    <skip>false</skip>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>repackage</id>
+                        <goals>
+                            <goal>repackage</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 23 - 0
src/main/java/com/lutao/tcp/server/TcpServerApplication.java

@@ -0,0 +1,23 @@
+package com.lutao.tcp.server;
+
+import com.lutao.tcp.server.tcptest.BootNettyServer;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableAsync;
+
+@SpringBootApplication
+@EnableAsync
+public class TcpServerApplication implements CommandLineRunner {
+
+    public static void main(String[] args) {
+        //SpringApplication.run(TcpServerApplication.class, args);
+        new SpringApplication(TcpServerApplication.class).run(args);
+        System.out.println("TcpServerApplication start");
+    }
+
+    @Override
+    public void run(String... args) throws Exception {
+        new BootNettyServer().bind(5635);
+    }
+}

+ 197 - 0
src/main/java/com/lutao/tcp/server/tcptest/BootNettyChannelInboundHandlerAdapter.java

@@ -0,0 +1,197 @@
+package com.lutao.tcp.server.tcptest;
+
+import cn.hutool.json.JSONUtil;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+
+@Slf4j
+@Component
+public class BootNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter {
+
+    private static BootNettyChannelInboundHandlerAdapter nettyServerHandler;
+    @PostConstruct
+    public void init() {
+        nettyServerHandler = this;
+    }
+
+    /**
+     * 从客户端收到新的数据时,这个方法会在收到消息时被调用
+     *
+     * @param ctx
+     * @param msg
+     */
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception, IOException {
+        String json = (String) msg;
+        //log.info(json);
+        try{
+            if (msg == null) {
+                log.error("======加载客户端报文为空======【" + ctx.channel().id() + "】" + " :" + json);
+                return;
+            }
+         if (JSONUtil.isJson(json)){
+             JSONObject jsonObject = JSON.parseObject(json);
+             log.info("======加载客户端报文======【" + ctx.channel().id() + "】" + " :" + jsonObject.toJSONString());
+         }else{
+             log.info("======无法转换为json======【" + ctx.channel().id() + "】" + " :" + json);
+         }
+            //回应客户端
+        ctx.write(ctx.channel().id() + "服务端已成功接收数据!");
+        }catch (Exception e){
+            e.printStackTrace();
+        }finally {
+
+
+        }
+    }
+
+
+    /**
+     * 从客户端收到新的数据、读取完成时调用
+     *
+     * @param ctx
+     */
+    @Override
+    public void channelReadComplete(ChannelHandlerContext ctx) throws IOException {
+        log.info("channelReadComplete");
+        ctx.flush();
+    }
+
+    /**
+     * 当出现 Throwable 对象才会被调用,即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
+     *
+     * @param ctx
+     * @param cause
+     */
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException {
+        log.info("exceptionCaught");
+        cause.printStackTrace();
+        ctx.close();//抛出异常,断开与客户端的连接
+    }
+
+    /**
+     * 客户端与服务端第一次建立连接时 执行
+     *
+     * @param ctx
+     * @throws Exception
+     */
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException {
+        super.channelActive(ctx);
+        ctx.channel().read();
+        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
+        String clientIp = insocket.getAddress().getHostAddress();
+        //此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
+        log.info("channelActive:"+clientIp+ctx.name());
+    }
+
+    /**
+     * 客户端与服务端 断连时 执行
+     *
+     * @param ctx
+     * @throws Exception
+     */
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException {
+        super.channelInactive(ctx);
+        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
+        String clientIp = insocket.getAddress().getHostAddress();
+        ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
+        log.info("channelInactive:"+clientIp);
+    }
+
+    /**
+     * 服务端当read超时, 会调用这个方法
+     *
+     * @param ctx
+     * @param evt
+     * @throws Exception
+     */
+    @Override
+    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException {
+        super.userEventTriggered(ctx, evt);
+        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
+        String clientIp = insocket.getAddress().getHostAddress();
+        ctx.close();//超时时断开连接
+        log.info("userEventTriggered:"+clientIp);
+    }
+
+    @Override
+    public void channelRegistered(ChannelHandlerContext ctx) throws Exception{
+        log.info("channelRegistered");
+    }
+
+    @Override
+    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception{
+        //当一个客户端断开连接或一个服务器完成其服务并关闭连接时
+        log.info("channelUnregistered");
+    }
+    /**
+     * 流量控制是一种拥塞控制机制,
+     * 用于防止发送方过多地发送数据,从而导致接收方过载。
+     * 当通道变得不可写时,这可能意味着接收方的缓冲区已满,
+     * 因此发送方需要停止发送数据,等待通道变得可写时再继续发送
+     * @throws Exception
+     */
+    @Override
+    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception{
+        // 通道变得可写,可以继续发送数据
+        log.info("Channel is writable, resuming data transmission.");
+    }
+    /**
+     * 广播数据十六进制,每两个字符为一组,
+     *如:09 57 79 30 30 30 30 30 30 30 30 30 30 30 41 30 30 35 30 30
+     * 再转为对应ASCII码,即可得到明文的uuid
+     * @param uuid
+     */
+    public String hexToASCII(String uuid) {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < uuid.length(); i += 2) {
+            String hex = uuid.substring(i, i + 2);
+            int decimal = Integer.parseInt(hex, 16);
+            char asciiChar = (char) decimal;
+            sb.append(asciiChar);
+        }
+        String result = sb.toString();
+        return result;
+    }
+    /**
+     * 将时间戳转换为yyyy-MM-dd HH:mm:ss格式的日期字符串。
+     * @param timestamp 时间戳(以毫秒为单位)
+     * @return 格式化后的日期字符串
+     */
+    public String timestampToDate(long timestamp) {
+        Instant instant = Instant.ofEpochSecond(timestamp); // 将时间戳转换为Instant对象
+        LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 将Instant对象转换为本地日期时间对象
+        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期格式
+        // 将日期时间对象格式化为字符串
+        String time = dateTime.format(formatter);
+        return time;
+    }
+    /**
+     * 将LocalDateTime转换为yyyy-MM-dd HH:mm:ss格式的日期字符串。
+     * @return 格式化后的日期字符串
+     */
+    public String LocalDateTimeToStr() {
+        // 获取当前日期时间
+        LocalDateTime now = LocalDateTime.now();
+        // 定义日期时间的格式
+        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+        // 将LocalDateTime格式化为字符串
+        String formattedDateTime = now.format(formatter);
+        return formattedDateTime;
+    }
+}

+ 45 - 0
src/main/java/com/lutao/tcp/server/tcptest/BootNettyChannelInitializer.java

@@ -0,0 +1,45 @@
+package com.lutao.tcp.server.tcptest;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelInitializer;
+import io.netty.handler.codec.DelimiterBasedFrameDecoder;
+import io.netty.handler.codec.Delimiters;
+import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
+import io.netty.handler.codec.string.StringDecoder;
+import io.netty.handler.codec.string.StringEncoder;
+import io.netty.util.CharsetUtil;
+
+/**
+ * 通道初始化
+ */
+public class BootNettyChannelInitializer<SocketChannel> extends ChannelInitializer<Channel> {
+
+    @Override
+    protected void initChannel(Channel ch) throws Exception {
+
+        ByteBuf delimiter = Unpooled.copiedBuffer("\r\n".getBytes(CharsetUtil.UTF_8));
+
+        // 添加DelimiterBasedFrameDecoder
+        ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8388608, delimiter));
+
+
+        //添加编解码,此处代码为解析tcp传过来的参数,为UTF-8格式,可以自定义解码格式
+        // ChannelOutboundHandler,依照逆序执行
+        ch.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
+
+        // 属于ChannelInboundHandler,依照顺序执行
+        ch.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
+
+
+        //ch.pipeline().addLast("framer", new Custom());
+
+        /**
+         * 自定义ChannelInboundHandlerAdapter
+         */
+        ch.pipeline().addLast(new BootNettyChannelInboundHandlerAdapter());
+
+    }
+
+}

+ 76 - 0
src/main/java/com/lutao/tcp/server/tcptest/BootNettyServer.java

@@ -0,0 +1,76 @@
+package com.lutao.tcp.server.tcptest;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.AdaptiveRecvByteBufAllocator;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import io.netty.channel.socket.SocketChannel;
+
+@Slf4j
+@Component
+public class BootNettyServer {
+
+    public void bind(int port) throws Exception {
+
+        /**
+         * 配置服务端的NIO线程组
+         * NioEventLoopGroup 是用来处理I/O操作的Reactor线程组
+         * bossGroup:用来接收进来的连接,workerGroup:用来处理已经被接收的连接,进行socketChannel的网络读写,
+         * bossGroup接收到连接后就会把连接信息注册到workerGroup
+         * workerGroup的EventLoopGroup默认的线程数是CPU核数的二倍
+         */
+        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
+        EventLoopGroup workerGroup = new NioEventLoopGroup();
+
+        try {
+            /**
+             * ServerBootstrap 是一个启动NIO服务的辅助启动类
+             */
+            ServerBootstrap serverBootstrap = new ServerBootstrap();
+            /**
+             * 设置group,将bossGroup, workerGroup线程组传递到ServerBootstrap
+             */
+            serverBootstrap = serverBootstrap.group(bossGroup, workerGroup);
+            /**
+             * ServerSocketChannel是以NIO的selector为基础进行实现的,用来接收新的连接,这里告诉Channel通过NioServerSocketChannel获取新的连接
+             */
+            serverBootstrap = serverBootstrap.channel(NioServerSocketChannel.class);
+            /**
+             * option是设置 bossGroup,childOption是设置workerGroup
+             * netty 默认数据包传输大小为1024字节, 设置它可以自动调整下一次缓冲区建立时分配的空间大小,避免内存的浪费最小初始化最大 (根据生产环境实际情况来定)
+             * 使用对象池,重用缓冲区
+             */
+            serverBootstrap = serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(60, 8388608, 16777216));
+            serverBootstrap = serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(60, 8388608, 16777216));
+            /**
+             * 设置 I/O处理类,主要用于网络I/O事件,记录日志,编码、解码消息
+             */
+            serverBootstrap = serverBootstrap.childHandler(new BootNettyChannelInitializer<SocketChannel>());
+
+            log.info("netty server start success!");
+            /**
+             * 绑定端口,同步等待成功
+             */
+            ChannelFuture f = serverBootstrap.bind(port).sync();
+            /**
+             * 等待服务器监听端口关闭
+             */
+            f.channel().closeFuture().sync();
+
+        } catch (InterruptedException e) {
+
+        } finally {
+            /**
+             * 退出,释放线程池资源
+             */
+            bossGroup.shutdownGracefully();
+            workerGroup.shutdownGracefully();
+        }
+
+    }
+}

+ 48 - 0
src/main/java/com/lutao/tcp/server/tcptest/Custom.java

@@ -0,0 +1,48 @@
+//package com.lutao.tcp.server.tcptest;
+//
+//import io.netty.buffer.ByteBuf;
+//import io.netty.buffer.Unpooled;
+//import io.netty.channel.ChannelHandlerContext;
+//import io.netty.handler.codec.ByteToMessageDecoder;
+//import io.netty.util.CharsetUtil;
+//
+//import java.util.List;
+//
+//public class Custom extends ByteToMessageDecoder {
+//    private final ByteBuf delimiter;
+//
+//    public Custom() {
+//        delimiter = Unpooled.copiedBuffer("\r\n".getBytes(CharsetUtil.UTF_8));
+//    }
+//
+//    @Override
+//    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+//        int delimiterLength = delimiter.readableBytes();
+//        int index = indexOf(in, delimiter);
+//
+//        if (index >= 0) {
+//            ByteBuf frame = in.readRetainedSlice(index - in.readerIndex());
+//            in.skipBytes(delimiterLength);
+//            out.add(frame);
+//        }
+//    }
+//
+//    private int indexOf(ByteBuf buffer, ByteBuf delimiter) {
+//        for (int i = buffer.readerIndex(); i < buffer.writerIndex(); i++) {
+//            int j = 0;
+//            while (j < delimiter.capacity() && buffer.getByte(i + j) == delimiter.getByte(j)) {
+//                j++;
+//            }
+//            if (j == delimiter.capacity()) {
+//                return i;
+//            }
+//        }
+//        return -1;
+//    }
+//
+//    @Override
+//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+//        cause.printStackTrace();
+//        ctx.close();
+//    }
+//}

+ 35 - 0
src/main/java/com/lutao/tcp/server/tcptest/CustomDelimiterDecoder.java

@@ -0,0 +1,35 @@
+//package com.lutao.tcp.server.tcptest;
+//
+//import io.netty.buffer.ByteBuf;
+//import io.netty.buffer.Unpooled;
+//import io.netty.channel.ChannelHandlerContext;
+//import io.netty.handler.codec.ByteToMessageDecoder;
+//import io.netty.util.CharsetUtil;
+//
+//import java.util.List;
+//
+//public class CustomDelimiterDecoder extends ByteToMessageDecoder {
+//
+//    private final ByteBuf delimiter;
+//
+//    public CustomDelimiterDecoder() {
+//        delimiter = Unpooled.copiedBuffer("\r\n".getBytes(CharsetUtil.UTF_8));
+//    }
+//
+//    @Override
+//    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+//        int delimiterLength = delimiter.readableBytes();
+//        int index = in.indexOf(in.readerIndex(), in.writerIndex(), delimiter.readByte());
+//        if (index != -1) {
+//            ByteBuf frame = in.readRetainedSlice(index - in.readerIndex());
+//            in.skipBytes(delimiterLength); // 跳过分隔符
+//            out.add(frame);
+//        }
+//    }
+//
+//    @Override
+//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+//        cause.printStackTrace();
+//        ctx.close();
+//    }
+//}

+ 2 - 0
src/main/resources/application.yml

@@ -0,0 +1,2 @@
+server:
+  port: 8081

+ 13 - 0
src/test/java/com/lutao/tcp/server/TcpServerApplicationTests.java

@@ -0,0 +1,13 @@
+package com.lutao.tcp.server;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class TcpServerApplicationTests {
+
+    @Test
+    void contextLoads() {
+    }
+
+}