如何在连接到spring websocket时向用户发送消息

时间:2016-05-20 07:15:20

标签: java spring stomp spring-websocket

我想在连接到spring websocket时向用户发送消息,我已

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Autowired
    private GenervicSerice<User> 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;
    }

}

通过此我获得有关新连接用户的信息,但updateNotificationAndBroadcast()中的方法WebSocketConfig未向新登录用户发送邮件。

2 个答案:

答案 0 :(得分:1)

我会创建SessionSubscribeEvent侦听器并在其中使用SimpMessagingTemplate

顺便说一下,configureClientInboundChannel只被调用一次(不是每个连接的用户)。所以你必须处理在拦截器内发送消息。

尝试这样的事情:

@Service
public class SomeSubscribeListener {

    private SimpMessagingTemplate template;

    @Autowired
    public SomeSubscribeListener(SimpMessagingTemplate template) {
        this.template = template;
    }

    @EventListener
    public void handleSubscribeEvent(SessionSubscribeEvent event) {
        template.convertAndSendToUser(event.getUser().getName(), "/queue/notify", "GREETINGS");
    }
}

我希望这会有所帮助

答案 1 :(得分:1)

您需要一个Websocketconfig文件:

counts.txt:

0
counter_update.php:

<?php

$count = trim(file_get_contents('counts.txt'));
$count++;
file_put_contents('counts.txt', $count);
?>

并声明另一个@Configuration文件:

package mx.config.ws;
@EnableScheduling
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
   @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
       registry.addEndpoint("/chat").withSockJS()
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    ...
    }
}

接下来创建ApplicationListener接口的实现。自动拦截STOMP连接

package mx.config.ws;
@Configuration
public class WebSocketHandlersConfig {

    @Bean
    public StompConnectEvent webSocketConnectHandler() {
        return new StompConnectEvent();
    }

    @Bean
    public StompDisconnectEvent webSocketDisconnectHandler() {
        return new StompDisconnectEvent();
    }
}

检查此链接是否有一些信息:
http://www.sergialmar.com/2014/03/detect-websocket-connects-and-disconnects-in-spring-4/