文章目录

概要

        使用springboot创建一个TCP服务端与TCP客户端

流程

TCP服务端

服务端ip是采取的本机ip,port可以自定义设置

例如本机ip:192.168.1.100:5201

创建流程

使用hutool工具

文档地址:NIO封装-NioServer和NioClient (hutool.cn)

导入hutool依赖后,进行tcp服务端的创建

 

static HashMap<String, NioServer> tcpServerMap = new HashMap<>();

 public void init(Integer port) {
        try {
            if (!tcpServerMap.containsKey(String.valueOf(port))) {
                NioServer server = new NioServer(port);
                tcpServerMap.put(String.valueOf(port), server);
                server.setChannelHandler((sc) -> {
                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    try {
                        //从channel读数据到缓冲区
                        int readBytes = sc.read(readBuffer);
                        if (readBytes > 0) {
                            //Flips this buffer.  The limit is set to the current position and then
                            // the position is set to zero,就是表示要从起始位置开始读取数据
                            readBuffer.flip();
                            //eturns the number of elements between the current position and the  limit.
                            // 要读取的字节长度
                            byte[] bytes = new byte[readBuffer.remaining()];
                            //将缓冲区的数据读到bytes数组
                            readBuffer.get(bytes);
                            String body = StrUtil.utf8Str(bytes);
                            log.info("[{}]: {}", sc.getRemoteAddress(), body);
                            // 回写
                            doWrite(sc, body);
                        } else if (readBytes < 0) {
                            IoUtil.close(sc);
                        }
                    } catch (IOException e) {
                        log.error("读取服务器消息失败! -------> ", e);
                    }
                });
                server.listen();
            }

        } catch (Exception e) {
            log.error("初始化失败,{}", e.getMessage(), e);
        }

    }

服务端监听数据

public void doWrite(SocketChannel channel, String response) throws IOException {
        log.info("收到服务监听到的消息 -----> {}", response);

        JSONObject jsonObject = JSONObject.parseObject(response);
        log.info("服务器监听到的消息转为json -----> {}", jsonObject);

        //将缓冲数据写入渠道,返回给客户端
        channel.write(BufferUtil.createUtf8("数据"));
}

TCP客户端

通过ip,port来创建,采用TCP长连接

 

    static HashMap<String, NioClient> tcpClientMap = new HashMap<>();

public void init(Integer port, String ip) {
        try {
            if (!tcpClientMap.containsKey(ip)) {
                NioClient client = new NioClient(ip, port);
                tcpClientMap.put(ip, client);

                // 创建TCP服务后发送登录验证消息
                String msg = getLoginString();
                if (msg == null || msg.isEmpty()) {
                    log.info("获取登录信息失败-----> msg为null 或者 \"\"");
                } else {
                    log.info("登录string-----> {}", msg);
                    byte[] bytes = msg.getBytes();
                    log.info("登录string 字节数组-----> {}", msg.getBytes());
                    client.write(ByteBuffer.wrap(bytes));
                }

                // 开始监听TCP消息
                client.setChannelHandler((sc) -> {
                    try {
                        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                        int readBytes = sc.read(readBuffer);
                        if (readBytes > 0) {
                            readBuffer.flip();
                            byte[] bytes = new byte[readBuffer.remaining()];
                            readBuffer.get(bytes);

                            String body = StrUtil.utf8Str(bytes);

                            log.info("TCP监听的消息----》[{}]: {}", sc.getRemoteAddress(), body);

                        

                        } else if (readBytes < 0) {
//                        sc.close();
                        }
                    } catch (Exception e) {
                        log.error("异常----》{}", e.getMessage(), e);
                    }
                });
                client.listen();
            }
        } catch (Exception e) {
            log.error("启动TCP服务失败!", e);
        }
    }
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐