• 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;
    
  • 相关阅读:
    iOS开发
    Xcode
    UITextField
    iOS
    过场动画
    iOS 网络状态监听和检查,
    线程互动,GCD小应用,(功能实现并代码聚集---加载动画,弹框AlertView定时消失。)
    drawRect: 小注
    FMDB_and_Sqlite3
    UIGestureRecognizer手势。
  • 原文地址:https://www.cnblogs.com/Leechg/p/15572408.html
Copyright © 2020-2023  润新知