zoukankan      html  css  js  c++  java
  • Springboot + Stomp + React 实现通过前后端通信

    后端 Springboot

    maven依赖

    使用springboot官方starter

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>
    

    添加配置类

    @Configuration
    @EnableWebSocketMessageBroker  
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            config.enableSimpleBroker("/wshub/topic" ); 
        }
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/wshub/webServer").setAllowedOrigins("*").withSockJS(); 
        }
    }
    

    添加controller

    
     
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.messaging.handler.annotation.MessageMapping;
    import org.springframework.messaging.simp.SimpMessagingTemplate;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/wshub")
    public class WSHubController {
        @Autowired
        public SimpMessagingTemplate template;
    
    
        @MessageMapping("/subscribe")
        public void subscribe(ReceiveMessage rm) {
            for (int i = 1; i <= 20; i++) {
                // 广播使用convertAndSend方法,第一个参数为目的地,和js中订阅的目的地要一致
                template.convertAndSend("/wshub/topic/getResponse", rm.getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    参考 https://www.cnblogs.com/hhhshct/p/8849449.html

    前端

    添加依赖

     yarn add sockjs-client 
     yarn add webstomp-client
    

    发起连接

    import { Button } from "antd"
    import { useEffect, useState } from "react";
    import SockJS from "sockjs-client";
    import Stomp from "webstomp-client";
    
    const MsgTestView = () => {
        const [stomp, setStomp] = useState();
        const [newResponse, setNewResponse] = useState();
        const [responses, setResponses] = useState([])
    
        const [connected, setConnected] = useState(false)
    
    
        const connectServer = () => { 
            const socket = new SockJS("https://172.16.1.219:3000/server/wshub/webServer");
            const stompClient = Stomp.over(socket);
            stompClient.connect(
                {},
                frame => {
                    setConnected(true)
                    console.log("Frame:");
                    console.log(frame);
                    stompClient.subscribe("/wshub/topic/monitor", tick => {
                        console.log("tick received:");
                        console.log(tick);
                        let newMessage = { message: tick.body };
                        setNewResponse(newMessage)
                        console.log("Now the messages array is:");
    
    
                    });
                },
                error => {
                    console.log(error);
    
                }
            );
            window.stomp = stompClient; 
    
            setStomp(stompClient)
    
        }
    
        const send = () => {
            stomp.send('/subscribe', JSON.stringify({ 'name': "sdfasdfsad" })) 
        }
    
        useEffect(() => {
            if (newResponse) {
                setResponses([newResponse, ...responses])
            }
        }, [newResponse])
    
        useEffect(() => {
         
        }, [])
    
        return <div>
             
            <div>
                {
                    responses.map(r => <div>{r.message}</div>)
    
                }
            </div>
        </div>
    }
    
    export default MsgTestView;
    
  • 相关阅读:
    解决方案solution
    Marshal类
    鼠标钩子WH_MOUSE_LL和WH_MOUSE的区别
    DllImport
    打包.py文件成.exe
    C++定义全部变量注意项
    类.cpp文件不识别类.h所定义的结构体问题
    C++判断文件是否存在
    博客专栏
    软件测试基础知识
  • 原文地址:https://www.cnblogs.com/Leechg/p/15572408.html
Copyright © 2011-2022 走看看