我想在连接到spring websocket时向用户发送消息,我已经
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Autowired
private GenervicSerice userService;
@Autowired
private SimpMessagingTemplate template;
private CurrentUser currnetUser;
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
// TODO Auto-generated method stub
stompEndpointRegistry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue/", "/topic/", "/exchange/");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(myChannelInterception());
try {
updateNotificationAndBroadcast();
} catch (Exception e) {
return;
}
}
@Bean
public MyChannelInterception myChannelInterception() {
return new MyChannelInterception();
}
private void updateNotificationAndBroadcast() {
try {
template.convertAndSend("/queue/notify", "Greetings");
} catch (Exception e) {
System.out.println("Error message is " + e.getMessage() + "\n\n\n" + "Caused by " + e.getCause()
);
}
}
}
MyChannelInterception类是
public class ImtehanChannelInterception extends ChannelInterceptorAdapter {
private CurrentUser currnetUser;
@Override
public Message> preSend(Message> message, MessageChannel channel) {
MessageHeaders headers = message.getHeaders();
SimpMessageType type = (SimpMessageType) headers.get("simpMessageType");
String simpSessionId = (String) headers.get("simpSessionId");
currnetUser = new CurrentUser();
if (type == SimpMessageType.CONNECT) {
Principal principal = (Principal) headers.get("simpUser");
currnetUser.setCurrentUserEmail(principal.getName());
System.out.println("WsSession " + simpSessionId
+ " is connected for user " + principal.getName());
} else if (type == SimpMessageType.DISCONNECT) {
System.out.println("WsSession " + simpSessionId
+ " is disconnected");
}
return message;
}
}
通过这个我获得有关新连接用户的信息,但WebSocketConfig中的方法updateNotificationAndBroadcast()不向新登录用户发送消息.