简体   繁体   English

春+的WebSocket + STOMP。 给特定会话的消息(非用户)

[英]Spring+WebSocket+STOMP. Message to specific session (NOT user)

I am trying to set up basic message broker on Spring framework, using a recipe I found here 我正在尝试使用我在此处找到的配方在Spring框架上设置基本消息代理

Author claims it has worked well, but I am unable to receive messages on client, though no visible errors were found. 作者声称它运行良好,但我无法在客户端收到消息,但没有发现可见的错误。

Goal: 目标:

What I am trying to do is basically the same - a client connects to server and requests some async operation. 我想要做的基本上是相同的 - 客户端连接到服务器并请求一些异步操作。 After operation completes the client should receive an event. 操作完成后,客户端应该收到一个事件。 Important note: client is not authenticated by Spring, but an event from async back-end part of the message broker contains his login, so I assumed it would be enough to store concurrent map of Login-SessionId pairs for sending messages directly to particular session. 重要说明:Spring没有对客户端进行身份验证,但是来自消息代理的异步后端部分的事件包含他的登录,因此我认为存储Login-SessionId对的并发映射就足以将消息直接发送到特定会话。

Client code: 客户代码:

//app.js

var stompClient = null;
var subscription = '/user/queue/response';

//invoked after I hit "connect" button
function connect() {
//reading from input text form
var agentId = $("#agentId").val();

var socket = new SockJS('localhost:5555/cti');
stompClient = Stomp.over(socket);
stompClient.connect({'Login':agentId}, function (frame) {
    setConnected(true);
    console.log('Connected to subscription');
    stompClient.subscribe(subscription, function (response) {
        console.log(response);
    });
});

}

//invoked after I hit "send" button
function send() {

var cmd_str = $("#cmd").val();
var cmd = {
    'command':cmd_str
};
console.log("sending message...");
stompClient.send("/app/request", {}, JSON.stringify(cmd));
console.log("message sent");
}

Here is my configuration. 这是我的配置。

//message broker configuration

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{


@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    /** queue prefix for SUBSCRIPTION (FROM server to CLIENT)  */
    config.enableSimpleBroker("/topic");
    /** queue prefix for SENDING messages (FROM client TO server) */
    config.setApplicationDestinationPrefixes("/app");
}


@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {

    registry
            .addEndpoint("/cti")
            .setAllowedOrigins("*")
            .withSockJS();
}

}

Now, after basic config I should implement an application event handler to provide session-related information on client connect. 现在,在基本配置之后,我应该实现一个应用程序事件处理程序来提供有关客户端连接的会话相关信

//application listener

@Service
public class STOMPConnectEventListener implements ApplicationListener<SessionConnectEvent> {

@Autowired
//this is basically a concurrent map for storing pairs "sessionId - login"
WebAgentSessionRegistry webAgentSessionRegistry;

@Override
public void onApplicationEvent(SessionConnectEvent event) {
    StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());

    String agentId = sha.getNativeHeader("Login").get(0);
    String sessionId = sha.getSessionId();

    /** add new session to registry */
    webAgentSessionRegistry.addSession(agentId,sessionId);

    //debug: show connected to stdout
    webAgentSessionRegistry.show();

}
}

All good so far. 到目前为止都很好。 After I run my spring webapp in IDE and connected my "clients" from two browser tabs I got this in IDE console: 在IDE中运行我的spring webapp并从两个浏览器选项卡连接我的“客户端”后,我在IDE控制台中得到了这个:

session_id / agent_id
-----------------------------
|kecpp1vt|user1|
|10g5e10n|user2|
-----------------------------

Okay, now let's try to implement message mechanics. 好的,现在让我们尝试实现消息机制。

//STOMPController


@Controller
public class STOMPController {

@Autowired
//our registry we have already set up earlier
WebAgentSessionRegistry webAgentSessionRegistry;
@Autowired
//a helper service which I will post below
MessageSender sender;

@MessageMapping("/request")
public void handleRequestMessage() throws InterruptedException {

    Map<String,String> params = new HashMap(1);
    params.put("test","test");
    //a custom object for event, not really relevant
    EventMessage msg = new EventMessage("TEST",params);

    //send to user2 (just for the sake of it)
    String s_id = webAgentSessionRegistry.getSessionId("user2");
    System.out.println("Sending message to user2. Target session: "+s_id);
    sender.sendEventToClient(msg,s_id);
    System.out.println("Message sent");

}
}

A service to send messages from any part of the application: 从应用程序的任何部分发送消息的服务:

//MessageSender

@Service
public class MessageSender implements IMessageSender{

@Autowired
WebAgentSessionRegistry webAgentSessionRegistry;
@Autowired
SimpMessageSendingOperations messageTemplate;

private String qName = "/queue/response";

private MessageHeaders createHeaders(String sessionId) {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    headerAccessor.setSessionId(sessionId);
    headerAccessor.setLeaveMutable(true);
    return headerAccessor.getMessageHeaders();
}

@Override
public void sendEventToClient(EventMessage event,String sessionId) {
    messageTemplate.convertAndSendToUser(sessionId,qName,event,createHeaders(sessionId));
}
}

Now, let's try to test it. 现在,让我们试试吧。 I run my IDE, opened Chrome and created 2 tabs form which I connected to server. 我运行我的IDE,打开Chrome并创建了2个选项卡,我连接到服务器。 User1 and User2. User1和User2。 Result console: 结果控制台:

 session_id / agent_id
    -----------------------------
    |kecpp1vt|user1|
    |10g5e10n|user2|
    -----------------------------
Sending message to user2. Target session: 10g5e10n
Message sent

But, as I mentioned in the beginning - user2 got absolutely nothing, though he is connected and subscribed to "/user/queue/response". 但是,正如我在开始时提到的那样 - 尽管他已连接并订阅了“/ user / queue / response”,但user2却一无所获。 No errors either. 也没有错误。

A question is, where exactly I am missing the point? 一个问题是,我到底错过了哪一点? I have read many articles on the subject, but to no avail. 我已经阅读了很多关于这个主题的文章,但无济于事。 SPR-11309 says it's possible and should work. SPR-11309说这是可能的并且应该可行。 Maybe, id-s aren't actual session id-s? 也许,id-s不是实际的会话ID-s? And well maybe someone knows how to monitor if the message actually has been sent, not dropped by internal Spring mechanics? 好吧也许有人知道如何监控消息是否实际发送过,而不是内部Spring机制丢弃?

SOLUTION UPDATE: 解决方案更新:

A misconfigured bit: 错误配置的位:

//WebSocketConfig.java:
....
 @Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    /** queue prefix for SUBSCRIPTION (FROM server to CLIENT)  */
    // + parameter "/queue"
    config.enableSimpleBroker("/topic","/queue");
    /** queue prefix for SENDING messages (FROM client TO server) */
    config.setApplicationDestinationPrefixes("/app");
}
....

I've spent a day debugging internal spring mechanics to find out where exactly it goes wrong: 我花了一天时间调试内部弹簧力学,找出它究竟出错的地方:

//AbstractBrokerMessageHandler.java: 
....
protected boolean checkDestinationPrefix(String destination) {
    if ((destination == null) || CollectionUtils.isEmpty(this.destinationPrefixes)) {
        return true;
    }
    for (String prefix : this.destinationPrefixes) {
        if (destination.startsWith(prefix)) {
//guess what? this.destinationPrefixes contains only "/topic". Surprise, surprise
            return true;
        }
    }
    return false;
}
....

Although I have to admit I still think the documentation mentioned that user personal queues aren't to be configured explicitly cause they "already there". 虽然我不得不承认我仍然认为文档提到用户个人队列没有明确配置导致他们“已经存在”。 Maybe I just got it wrong. 也许我错了。

Overall it looks good, but could you change from 总的来说它看起来不错,但你可以改变吗?

config.enableSimpleBroker("/topic");

to

config.enableSimpleBroker("/queue");

... and see if this works? ......看看这是否有效? Hope this help. 希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM