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;
    
  • 相关阅读:
    FileItem类的常用方法
    spring mvc(注解)上传文件的简单例子
    Linux下安装Tomcat服务器和部署Web应用
    防止表单重复提交的几种策略
    Rancher 2.0 学习目录
    Prometheus 学习目录
    k8s学习目录
    python之路——目录
    Mac OS X生成RSA公钥和私钥
    Django设置 DEBUG=False后静态文件无法加载解决
  • 原文地址:https://www.cnblogs.com/Leechg/p/15572408.html
Copyright © 2011-2022 走看看