Search code examples
javascriptspring-bootwebsocketwildflystomp

WebSocket stomp client subscribe for some devices are not working


I am trying to implement a spring boot chat application using WebSocket stomp client. If I send messages from one device to 4,5 devices then some are getting the messages and some are not. Some can send messages but don't receive any message and some are working completely fine. My application is running on wildfly server and the URL is over https.

Here is my js file. From my JSP page I am calling sendMsg with all parameter and through render method I am attaching the response with JSP using Handlebars.

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);
}

Here is my WebSocket configuration file:

@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");

    }

}

This is the controller. I always save all messages on the database that are coming through WebSocket that's why I can be sure that all devices can send messages as they have been saved on the database.

@Controller

@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);

        
    }

}

I can not find anything similar this issue. Please help me with right information and suggestion, and if anyone faced same kind of problem please share with me.


Solution

  • The problem was solved after configuring RabbitMQ Stomp Broker as a message broker instead of SimpleBroker.

    Current WebSocket configuration:

    @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);
        }
    
    } 
    

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

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