有没有一种方法可以在春天从常规方法发送websocket消息



我正在构建web应用程序。提供了管理员和用户角色。当用户执行某个操作时,管理员收到一条消息,表示发生了什么事情。用户登录时正在建立Websocket连接。有没有一种方法可以不为用户创建ws连接,只使用HHTP协议发送消息,只从控制器方法发送ws消息?

现在我有了这些设置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOriginPatterns("*").withSockJS();
}
}
@Controller
public class NotificationController {
@MessageMapping("/notification")
@SendTo("/topic/test")
public Notification getNotification(Notification notification) {
return notification;
}
}

是的,这是可能的
必须使用@Autowire或构造函数注入SimpleMessagingTemplate。

private final SimpMessagingTemplate simpMessagingTemplate;
public ConstructorName(SimpMessagingTemplate simpMessagingTemplate){
this.simpMessagingTemplate = simpMessagingTemplate;
}

在您的控制器或要向客户端发送消息的函数中,使用convertAndSendToUser函数。

simpMessagingTemplate.convertAndSendToUser("userId","/private", messageData);

在javascript客户端。

var Sock = new SockJS('http://localhost:8080/ws');
stompClient = over(Sock);
stompClient.connect({}, onConnected, onError);
stompClient.subscribe('/topic/' + userId + '/private', onMessageReceived);

最新更新