简体   繁体   English

java spring websocket发送来自其他应用程序的回复

[英]java spring websocket send reply from other application

I have two different java spring applications. 我有两个不同的java spring应用程序。 First one sends a message using websocket and it works fine. 第一个使用websocket发送消息,它工作正常。

client: 客户:

var socket = new SockJS('http://localhost:8080/myapp/hello');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/greeting', function(greeting){
                    console.log(greeting.body);
                    //showGreeting(JSON.parse(greeting.body).content);
                });
            });

Server: 服务器:

@MessageMapping("/send/{widgetId}")
    public Greeting userMessage(@DestinationVariable String widgetId,
            UserMessageWrapper userMessageWrapper) throws Exception {
        dispatchMessage(widgetId, userMessageWrapper.getUserToken(),
                userMessageWrapper.getMessage(), userMessageWrapper.getUserAgent());
        return new Greeting("asdasdsa");
    }

It works fine, but I need to send a reply to this message from other java application on other server. 它工作正常,但我需要从其他服务器上的其他Java应用程序发送此消息的回复。 I have a quartz job there and it scans db and sends replies to subscribed clients using websockets. 我在那里有一个石英工作,它扫描数据库并使用websockets将订阅客户端的回复发送给订阅客户端。 I want every client to receive only message for him, no broadcasting. 我希望每个客户只收到他的消息,没有广播。

public void callJSWebSocket(){
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor
            .create(SimpMessageType.MESSAGE);
    headerAccessor.setSubscriptionId("sub-0");
    headerAccessor.setLeaveMutable(true);

    messagingTemplate.convertAndSendToUser("user","/topic/greeting",
            "asdsadasd1212");
}

and configuration in both cases: 和两种情况下的配置:

@Configuration
@EnableWebSocketMessageBroker

    public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            config.enableSimpleBroker("/topic");
            config.setApplicationDestinationPrefixes("/ws");
        }

        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/hello").setAllowedOrigins("*").withSockJS();
        }

    }

I don't understand how to send message properly from other application. 我不明白如何从其他应用程序正确发送消息。 I guess I need to retrieve and store sessionId somewhere and then use for replying. 我想我需要在某处检索并存储sessionId然后用于回复。 Also, should I create config and controller for replying and what I am doing wrong? 另外,我应该创建用于回复的配置和控制器以及我做错了什么?

Fortunately I have managed to solve this situation. 幸运的是,我设法解决了这种情况。 First, I didn't find a way to interact with page directly from other application and I believe that it's not possible, because connection is required. 首先,我没有找到直接从其他应用程序与页面交互的方法,我认为这是不可能的,因为需要连接。 I decided to use a Jersey endpoint on first app that has a websocket connection to the page. 我决定在第一个应用程序上使用Jersey端点,该应用程序与页面具有websocket连接。 So, the second app calls REST url of the first app and then first app sends websocket message. 因此,第二个应用程序调用第一个应用程序的REST URL,然后第一个应用程序发送websocket消息。

IMPORTANT IMPORTANT!!!!! 重要的重要!!!!!

If you have in your app a "/" context that mapped, for example, to spring-mvc, make it /mvc or anything else. 如果你的应用程序中有一个“/”上下文,例如,映射到spring-mvc,make / mvc或其他任何内容。 Because if you have more than one context in spring (root and servlet contexts), spring websocket messaging infrastructure creates N sets of beans where N is number of your contents. 因为如果在spring(root和servlet上下文)中有多个上下文,spring websocket消息传递基础结构会创建N组bean,其中N是内容的编号。 So I faced a situation when WS session was registered in one context, but session check, convertAndSend method, etc, runned in other context. 所以我遇到了WS会话在一个上下文中注册的情况,但会话检查,convertAndSend方法等在其他上下文中运行。 I spent some hours on that. 我花了几个小时。 If you see a situation when you can't send a message to subscribed session, please go to 如果您看到无法向订阅会话发送消息的情况,请转到

org.springframework.messaging.simp.broker.DefaultSubscriptionRegistry#getSubscriptions(String destination, Message<?> message). 

And if you see that 如果你看到了

subscriptionRegistry.getAllSubscriptions()

is empty, please check your "/" context and make it not "/". 是空的,请检查您的“/”上下文并使其不是“/”。

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

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