我想将邮件从服务器发送到连接的客户端。我试图通过使用Web套接字来做到这一点。但它没有用......
我的HTML视图中的Javascript代码:
socket = new WebSocket('ws://localhost:8080/messages');
socket.onmessage = function(e) {
console.log(e);
}
Spring配置类:
@Configuration
@EnableWebSocketMessageBroker
@Import(WebSocketAutoConfiguration.class)
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(final MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/messages");
}
}
发送消息的服务类:
@Service
public class MessageSender {
@Autowired
private SimpMessagingTemplate messagingTemplate;
public void sendMessage(final String message) {
this.messagingTemplate.convertAndSend("/", message);
}
}
实际上客户端什么也没收到。 必须设置什么目的地才能向客户端发送消息?
答案 0 :(得分:0)
根据您的配置,您正在使用STOMP over WebSocket http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-enable
正确使用将是:
var socket = new WebSocket("/spring-websocket-portfolio/portfolio");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
})
Open Dev控制台,STOMP打印好日志:)