springboot项目添加TCP接口数据上传/下发

一般在启动类上添加

注意:一般检测TCP传输的数据软件----Sockit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@SpringBootApplication
 
public class Application extends <strong>SpringBootServletInitializer</strong> implements <strong>CommandLineRunner</strong> {
 
    @Autowired     <strong> //注意此处将要用的TCP进行调用</strong>
    TcpSocketServer tcpSocketServer;<br>
    public static void main(String[] args)throws IOException {
        SpringApplication.run(Application.class, args);
    }
    @Override      <strong>//重写run方法,来对TCP数据进行操作</strong>
    public void run(String... args) throws Exception {
        tcpSocketServer.startSocketServer(port);    <strong> //注:此处port绑定端口号</strong>
    }
 
     
}

 在 tcpSocketServer 内:   注意:一般涉及TCP接口的项目都是关于指令上传和下发的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@Component
@Slf4j      //前提是 导入了lombok的包
public class TcpSocketServer extends BaseController {
    @Autowired
    TcpServices tcpServices;
    @Autowired
    XxxService xxxService;
     
    private Charset cs = Charset.forName("UTF-8");
    //接受数据缓冲区
    private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);
    //发送数据缓冲区
    private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);
    //监听器
    private static Selector selector;
 
    private static String   responseMsg;
    /**
     * 启动socket服务,开启监听
     *
     * @param port
     * @throws IOException
     */
    public  void startSocketServer(int port) {
        try {
            //打开通信信道
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置为非阻塞
            serverSocketChannel.configureBlocking(false);
            //获取套接字
            ServerSocket serverSocket = serverSocketChannel.socket();
            //绑定端口号
            serverSocket.bind(new InetSocketAddress(port));
            //打开监听器
            selector = Selector.open();
            //将通信信道注册到监听器
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
 
            //监听器会一直监听,如果客户端有请求就会进入相应的事件处理
            while (true) {
                selector.select();//select方法会一直阻塞直到有相关事件发生或超时
                Set<SelectionKey> selectionKeys = selector.selectedKeys();//监听到的事件
                for (SelectionKey key : selectionKeys) {
                    handle(key);
                }
                selectionKeys.clear();//清除处理过的事件
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 处理不同的事件
     *
     * @param selectionKey
     * @throws IOException
     */
    private void handle(SelectionKey selectionKey) throws IOException {
        ServerSocketChannel serverSocketChannel = null;
        SocketChannel socketChannel = null;
        String requestMsg = "";
        int count = 0;
        if (selectionKey.isAcceptable()) {
            //每有客户端连接,即注册通信信道为可读
            serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
            socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
        } else if (selectionKey.isReadable()) {
            socketChannel = (SocketChannel) selectionKey.channel();
            rBuffer.clear();
            count = socketChannel.read(rBuffer);
 
            //读取数据
            if (count > 0){
            rBuffer.flip(); //从缓存区头部开始读取数据操作               //缓存区读取到的数据                requestMsg = String.valueOf(cs.decode(rBuffer).array()); } //这里是处理从TCP接口上传的数据业务层,一般可以在业务层根据switch case来对不同数据进行分类方法处理xxxServices.dealMethods(requestMsg);  sBuffer = ByteBuffer.allocate(responseMsg.getBytes("UTF-8").length);   //一般responseMsg为从数据库或其他数据源处获取的数据字符串                      //此处为指令下发                           responseMsg=configurationMap.toString();        sBuffer.put(responseMsg.getBytes("UTF-8"));                                                
        sBuffer.flip();
        socketChannel.write(sBuffer);              
                }           socketChannel.close();
          }
        }
      }
    }

  

 

 

 

 

 


posted @   唯恐不及  阅读(5849)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示