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();
}
}
}
}
前端
添加依赖
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;