Search in sources :

Example 1 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project spring_boot by hryou0922.

the class MyChannelInterceptorAdapter method preSend.

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    System.out.println(this.getClass().getCanonicalName() + " preSend");
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
    StompCommand command = accessor.getCommand();
    // 检测用户订阅内容(防止用户订阅不合法频道)
    if (StompCommand.SUBSCRIBE.equals(command)) {
        System.out.println(this.getClass().getCanonicalName() + " 用户订阅目的地=" + accessor.getDestination());
        // 如果该用户订阅的频道不合法直接返回null前端用户就接受不到该频道信息
        return super.preSend(message, channel);
    } else {
        return super.preSend(message, channel);
    }
}
Also used : StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) StompCommand(org.springframework.messaging.simp.stomp.StompCommand)

Example 2 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project spring_boot by hryou0922.

the class MyChannelInterceptorAdapter method afterSendCompletion.

@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
    System.out.println(this.getClass().getCanonicalName() + " afterSendCompletion");
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
    StompCommand command = accessor.getCommand();
    if (StompCommand.SUBSCRIBE.equals(command)) {
        System.out.println(this.getClass().getCanonicalName() + " 订阅消息发送成功");
        this.simpMessagingTemplate.convertAndSend("/topic/getResponse", "消息发送成功");
    }
    // 如果用户断开连接
    if (StompCommand.DISCONNECT.equals(command)) {
        System.out.println(this.getClass().getCanonicalName() + "用户断开连接成功");
        simpMessagingTemplate.convertAndSend("/topic/getResponse", "{'msg':'用户断开连接成功'}");
    }
    super.afterSendCompletion(message, channel, sent, ex);
}
Also used : StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) StompCommand(org.springframework.messaging.simp.stomp.StompCommand)

Example 3 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project JavaForFun by gumartinm.

the class CustomChannelInterceptor method preSend.

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
    StompCommand command = accessor.getCommand();
    LOGGER.info("CustomChannelInterceptor preSend, StompCommand: " + command);
    LOGGER.info("CustomChannelInterceptor preSend, login: " + accessor.getLogin());
    long[] heartBeats = accessor.getHeartbeat();
    for (long heartBeat : heartBeats) {
        LOGGER.info("CustomChannelInterceptor preSend, heartBeat: " + heartBeat);
    }
    LOGGER.info("CustomChannelInterceptor preSend, destination: " + accessor.getDestination());
    LOGGER.info("CustomChannelInterceptor preSend, host: " + accessor.getHost());
    LOGGER.info("CustomChannelInterceptor preSend, message: " + accessor.getMessage());
    LOGGER.info("CustomChannelInterceptor preSend, sessionId: " + accessor.getSessionId());
    byte[] payload = (byte[]) message.getPayload();
    String stringPayload = new String(payload);
    LOGGER.info("CustomChannelInterceptor preSend, payload: " + stringPayload);
    return message;
}
Also used : StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) StompCommand(org.springframework.messaging.simp.stomp.StompCommand)

Example 4 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project JavaForFun by gumartinm.

the class SessionConnectListener method onApplicationEvent.

@Override
public void onApplicationEvent(SessionConnectEvent event) {
    LOGGER.info("SessionConnectEvent timestamp: " + event.getTimestamp());
    LOGGER.info("SessionConnectEvent user: " + event.getUser());
    LOGGER.info("SessionConnectEvent: " + event.toString());
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
    StompCommand command = accessor.getCommand();
    LOGGER.info("SessionConnectEvent, StompCommand: " + command);
    LOGGER.info("SessionConnectEvent, login: " + accessor.getLogin());
    long[] heartBeats = accessor.getHeartbeat();
    for (long heartBeat : heartBeats) {
        LOGGER.info("SessionConnectEvent, heartBeat: " + heartBeat);
    }
    LOGGER.info("SessionConnectEvent, destination: " + accessor.getDestination());
    LOGGER.info("SessionConnectEvent, host: " + accessor.getHost());
    LOGGER.info("SessionConnectEvent, message: " + accessor.getMessage());
    LOGGER.info("SessionConnectEvent, sessionId: " + accessor.getSessionId());
    LOGGER.info("SessionConnectEvent, subscriptionId: " + accessor.getSubscriptionId());
    byte[] payload = (byte[]) event.getMessage().getPayload();
    String stringPayload = new String(payload);
    LOGGER.info("SessionConnectEvent, payload: " + stringPayload);
}
Also used : StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) StompCommand(org.springframework.messaging.simp.stomp.StompCommand)

Example 5 with StompCommand

use of org.springframework.messaging.simp.stomp.StompCommand in project spring-framework by spring-projects.

the class StompSubProtocolHandler method handleMessageFromClient.

/**
 * Handle incoming WebSocket messages from clients.
 */
@Override
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage, MessageChannel outputChannel) {
    List<Message<byte[]>> messages;
    try {
        ByteBuffer byteBuffer;
        if (webSocketMessage instanceof TextMessage) {
            byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes());
        } else if (webSocketMessage instanceof BinaryMessage) {
            byteBuffer = ((BinaryMessage) webSocketMessage).getPayload();
        } else {
            return;
        }
        BufferingStompDecoder decoder = this.decoders.get(session.getId());
        if (decoder == null) {
            if (!session.isOpen()) {
                logger.trace("Dropped inbound WebSocket message due to closed session");
                return;
            }
            throw new IllegalStateException("No decoder for session id '" + session.getId() + "'");
        }
        messages = decoder.decode(byteBuffer);
        if (messages.isEmpty()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Incomplete STOMP frame content received in session " + session + ", bufferSize=" + decoder.getBufferSize() + ", bufferSizeLimit=" + decoder.getBufferSizeLimit() + ".");
            }
            return;
        }
    } catch (Throwable ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to parse " + webSocketMessage + " in session " + session.getId() + ". Sending STOMP ERROR to client.", ex);
        }
        handleError(session, ex, null);
        return;
    }
    for (Message<byte[]> message : messages) {
        StompHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        Assert.state(headerAccessor != null, "No StompHeaderAccessor");
        StompCommand command = headerAccessor.getCommand();
        boolean isConnect = StompCommand.CONNECT.equals(command) || StompCommand.STOMP.equals(command);
        boolean sent = false;
        try {
            headerAccessor.setSessionId(session.getId());
            headerAccessor.setSessionAttributes(session.getAttributes());
            headerAccessor.setUser(getUser(session));
            if (isConnect) {
                headerAccessor.setUserChangeCallback(user -> {
                    if (user != null && user != session.getPrincipal()) {
                        this.stompAuthentications.put(session.getId(), user);
                    }
                });
            }
            headerAccessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, headerAccessor.getHeartbeat());
            if (!detectImmutableMessageInterceptor(outputChannel)) {
                headerAccessor.setImmutable();
            }
            if (logger.isTraceEnabled()) {
                logger.trace("From client: " + headerAccessor.getShortLogMessage(message.getPayload()));
            }
            if (isConnect) {
                this.stats.incrementConnectCount();
            } else if (StompCommand.DISCONNECT.equals(command)) {
                this.stats.incrementDisconnectCount();
            }
            try {
                SimpAttributesContextHolder.setAttributesFromMessage(message);
                sent = outputChannel.send(message);
                if (sent) {
                    if (this.eventPublisher != null) {
                        Principal user = getUser(session);
                        if (isConnect) {
                            publishEvent(this.eventPublisher, new SessionConnectEvent(this, message, user));
                        } else if (StompCommand.SUBSCRIBE.equals(command)) {
                            publishEvent(this.eventPublisher, new SessionSubscribeEvent(this, message, user));
                        } else if (StompCommand.UNSUBSCRIBE.equals(command)) {
                            publishEvent(this.eventPublisher, new SessionUnsubscribeEvent(this, message, user));
                        }
                    }
                }
            } finally {
                SimpAttributesContextHolder.resetAttributes();
            }
        } catch (Throwable ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to send message to MessageChannel in session " + session.getId(), ex);
            } else if (logger.isErrorEnabled()) {
                // Skip unsent CONNECT messages (likely auth issues)
                if (!isConnect || sent) {
                    logger.error("Failed to send message to MessageChannel in session " + session.getId() + ":" + ex.getMessage());
                }
            }
            handleError(session, ex, message);
        }
    }
}
Also used : TextMessage(org.springframework.web.socket.TextMessage) Message(org.springframework.messaging.Message) WebSocketMessage(org.springframework.web.socket.WebSocketMessage) BinaryMessage(org.springframework.web.socket.BinaryMessage) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) ByteBuffer(java.nio.ByteBuffer) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) BinaryMessage(org.springframework.web.socket.BinaryMessage) BufferingStompDecoder(org.springframework.messaging.simp.stomp.BufferingStompDecoder) TextMessage(org.springframework.web.socket.TextMessage) Principal(java.security.Principal)

Aggregations

StompCommand (org.springframework.messaging.simp.stomp.StompCommand)14 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)10 Type (java.lang.reflect.Type)2 Principal (java.security.Principal)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 ServerPortInfoApplicationContextInitializer (org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer)2 Message (org.springframework.messaging.Message)2 SimpleMessageConverter (org.springframework.messaging.converter.SimpleMessageConverter)2 StompFrameHandler (org.springframework.messaging.simp.stomp.StompFrameHandler)2 StompHeaders (org.springframework.messaging.simp.stomp.StompHeaders)2 StompSession (org.springframework.messaging.simp.stomp.StompSession)2 StompSessionHandler (org.springframework.messaging.simp.stomp.StompSessionHandler)2 StompSessionHandlerAdapter (org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter)2 BinaryMessage (org.springframework.web.socket.BinaryMessage)2 TextMessage (org.springframework.web.socket.TextMessage)2 WebSocketMessage (org.springframework.web.socket.WebSocketMessage)2 WebSocketStompClient (org.springframework.web.socket.messaging.WebSocketStompClient)2 IOException (java.io.IOException)1 ByteBuffer (java.nio.ByteBuffer)1