簡體   English   中英

如何關閉彈簧服務器中的STOMP websocket

[英]How to close a STOMP websocket in a spring server


我正在使用spring-websocket和spring-messaging(版本4.2.2.RELEASE)通過功能齊全的代理(Apache ActiveMQ 5.10.0)在websockets上實現STOMP。
我的客戶只想訂閱目的地 - 也就是說他們不應該發送消息。 此外,我想對客戶可以訂閱的目的地實施更嚴格的控制。 在任何一種情況下(即客戶端嘗試發送消息或訂閱無效目的地)我希望能夠

  1. 發送適當的錯誤,和/或
  2. 關閉websocket

請注意,我的所有目的地都轉發給ActiveMQ。 我認為我可以在入站通道上實現ChannelInterceptor ,但是看看API我無法弄清楚如何實現我想要的。 這是可能的,驗證客戶端請求的最佳方法是什么? 我的websocket配置如下:

<websocket:message-broker
    application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/pushchannel"/>
    <websocket:stomp-broker-relay relay-host="localhost"
        relay-port="61613" prefix="/topic"
        heartbeat-receive-interval="300000" heartbeat-send-interval="300000" />
    <websocket:client-inbound-channel>
        <websocket:interceptors>
            <bean class="MyClientMessageInterceptor"/>
        </websocket:interceptors>
    </websocket:client-inbound-channel>
</websocket:message-broker>

您可以編寫入站攔截器並向客戶端發送相應的錯誤消息。

public class ClientInboundChannelInterceptor extends ChannelInterceptorAdapter {

@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

@Override
public Message<?> preSend(Message message, MessageChannel channel) throws IllegalArgumentException{
    StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message);
    logger.debug("logging command " + headerAccessor.getCommand());
    try {
          //write your logic here
        } catch (Exception e){
            throw new MyCustomException();
        }
    }

}

更新:

1)當你從ClientInboundChannelInterceptor拋出任何異常時,它將作為ERROR幀發送,你不必做任何特殊的事情。

2)我不確定關閉連接,但做一些像創建DISCONNECT標頭和發送它應該工作(我將嘗試測試這個並更新答案)。

SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT);
headerAccessor.setSessionId(sessionId);
headerAccessor.setLeaveMutable(true);

template.convertAndSendToUser(destination,new HashMap<>(),headerAccessor.getMessageHeaders());

訂閱時,您有以下選項之一發送錯誤。

1)從ClientInboundChannelInterceptor拋出異常。

2)在Handler/Controller ,添加@SubscribeMapping並返回框架。

@SubscribeMapping("your destination")
public ConnectMessage handleSubscriptions(@DestinationVariable String userID, org.springframework.messaging.Message message){
    // this is my custom class
    ConnectMessage frame= new ConnectMessage();
    // write your logic here
    return frame;
}

frame將直接發送給客戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM