我是 Spring 新手,这可能是一项基本任务,但是在我使用 stomp websocket 设置 Spring Boot 后,一个交互式网页就完成了,我可以将 json 对象推送到客户端网页,但我的目标是仅刷新客户端/用户的页面,我不需要 json 传输。 我只想在管理员注销用户后刷新用户的页面。
这是我的app.js
var stompClient = null;
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
} else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
var socket = new SockJS('/vira-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
}
function sendName() {
stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
$(function () {
$( "form" ).on('submit', function (e) {e.preventDefault();});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
我的配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/vira-websocket").withSockJS();
}
}
和 Controller
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(3000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
}
请您参考如下方法:
我不确定我完全理解你的问题,但如果你想刷新页面而不是推送 json,只需将 location.reload();
替换为 subscribe< 的回调
函数,这是第二个参数。
function connect() {
var socket = new SockJS('/vira-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
stompClient.subscribe('/topic/greetings', location.reload());
});
}
according to the documentation The client will send a STOMP SUBSCRIBE frame to the server and register the callback. Every time the server send a message to the client, the client will in turn call the callback with a STOMP Frame object corresponding to the message:
这意味着您的刷新将在您向订阅用户发送推送后被调用。