Search code examples
javawebsocketspring-websocketstompjava-websocket

Unable to Send Binary Data (byte[]) using SimpMessagingTemplate


I am able to send string messages to websocket using SimpMessagingTemplate.convertAndSend() method, but same is not working when I try to send byte[]. When I send byte[] to the websocket subscription channel, a websocket DISCONNECT event is getting triggered and connection is getting lost. Any Idea to send byte[] to websocket using SimpMessagingTemplate !!!!!

@Autowired
private SimpMessagingTemplate template;

String body = "Message to be Sent";

template.convertAndSend("/channel", body);   --------- working

template.convertAndSend("/channel", body.getBytes());   --------- Not working

Solution

  • Have you tried adding a custom message converter to the byte array?. Just override configureMessageConverters method.

    @Configuration
    public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
    
        @Override
        protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
            messages.simpTypeMatchers(
                    SimpMessageType.DISCONNECT, SimpMessageType.OTHER).permitAll();
            messages.anyMessage().authenticated();
        }
    
        @Override
        public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
            messageConverters.add(new ByteArrayMessageConverter());
            return false;
        }
    
        @Override
        protected boolean sameOriginDisabled() {
            return true;
        }
    }