【问题标题】:WebSocket stomp client subscribe for some devices are not workingWebSocket stomp 客户端订阅某些设备不工作
【发布时间】:2020-10-16 10:24:49
【问题描述】:

我正在尝试使用 WebSocket stomp 客户端 实现一个 Spring Boot 聊天应用程序。如果我从一台设备向 4,5 台设备发送消息,那么有些会收到消息,有些则不会。有些可以发送消息但没有收到任何消息,有些则完全正常。我的应用程序在 Wildfly 服务器上运行,并且 URL 超过 https

这是我的 js 文件。在我的 JSP 页面中,我使用所有参数调用 sendMsg,并通过渲染方法使用 Handlebars 将响应附加到 JSP。

if (!window.location.origin) {
    window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
const url = window.location.origin+contextPath;
let stompClient;
let selectedUser;
let newMessages = new Map();


function connectToChat(userName, topicName) {
    console.log("connecting to chat...")
    let socket = new SockJS(url + '/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("connected to: " + frame);
        stompClient.subscribe("/topic/decision-log", function (response) {
            let data = JSON.parse(response.body);
            
             var msg = data.message;
             var fromlogin = data.message;
             render(data.username, msg, fromlogin);
  
            
        });
    });
}
connectToChat("1", "decision-log");
function sendMsg(from, text, username) {

    stompClient.send("/app/chat/" + from, {}, JSON.stringify({
        fromLogin: from,
        message: text,
        topicName: topicName,
        username: username
    }));
}

function render(username, message, projectId) {

    var templateResponse = Handlebars.compile($("#message-response-template").html());
    var contextResponse = {
        username: username,
        response: message,
        date: date,
        projectId: projectId
    };

    setTimeout(function () {
        $chatHistoryList.append(templateResponse(contextResponse));
        scrollToBottom();
    }.bind(this), 1500);
}

这是我的 WebSocket 配置文件:

@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer{
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();

    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app").enableSimpleBroker("/topic");

    }

}

这是控制器。我总是将通过 WebSocket 传入的所有消息保存在数据库中,这就是为什么我可以确定所有设备都可以发送消息,因为它们已保存在数据库中。

@控制器

@AllArgsConstructor
public class MessageController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    private final DecisionLogService decisionLogService;


    @MessageMapping("/chat/{to}")
    public void sendMessage(@DestinationVariable String to, MessageModel message, Authentication authentication ) {
        
        simpMessagingTemplate.convertAndSend("/topic/decision-log", message);

        AuthResponse userDetails = (AuthResponse) authentication.getDetails();
        DecisionLogCreateRequest decisionLogCreateRequest = new DecisionLogCreateRequest();
        decisionLogCreateRequest.setDecision(message.getMessage());
        decisionLogCreateRequest.setProjectId(to);
        ServiceResponseExtended<Boolean> response = decisionLogService.addDecisionLog(userDetails.getAccessToken(), decisionLogCreateRequest);

        
    }

}

我找不到类似的问题。请帮助我提供正确的信息和建议,如果有人遇到同样的问题,请与我分享。

【问题讨论】:

    标签: javascript spring-boot websocket wildfly stomp


    【解决方案1】:

    将 RabbitMQ Stomp Broker 配置为消息代理而不是 SimpleBroker 后问题得到解决。

    当前 WebSocket 配置:

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer{
        @Value("${stomp-broker-relay-host}")
        private String RELAY_HOST;
    
        @Value("${stomp-broker-relay-port}")
        private String RELAY_PORT;
    
        @Value("${stomp-broker-login-user}")
        private String USER;
    
        @Value("${stomp-broker-login-pass}")
        private String PASS;
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
    
        }
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
    
            registry.setApplicationDestinationPrefixes("/app");
            registry.enableStompBrokerRelay("/topic").setRelayHost(RELAY_HOST).setRelayPort(Integer.parseInt(RELAY_PORT)).setClientLogin(USER)
                    .setClientPasscode(PASS);
        }
    
    } 
    

    参考: https://medium.com/@rameez.s.shaikh/build-a-chat-application-using-spring-boot-websocket-rabbitmq-2b82c142f85a

    https://www.javainuse.com/misc/rabbitmq-hello-world

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2018-08-01
      • 2021-01-16
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多