My linux world » Java Spring – WebSocket

Java Spring - WebSocket


Contents

Prerequistes

Please read : Java spring – quickstart

Server Side (Java)

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
	/* (non-Javadoc)
	 * @see org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer#configureMessageBroker(org.springframework.messaging.simp.config.MessageBrokerRegistry)
	 */
	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		// server will listen socket message in '/socket':
		config.setApplicationDestinationPrefixes("/socket");
 
		// and send back response to '/broker':
		config.enableSimpleBroker("/broker");
 
	}
	/* (non-Javadoc)
	 * @see org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer#registerStompEndpoints(org.springframework.web.socket.config.annotation.StompEndpointRegistry)
	 */
	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		// when user want to connect with sockJS : var socket = new SockJS('/connect'); //NOSONAR
		registry.addEndpoint("/connect").withSockJS();
	}
}

WebSocketController

@Controller
public class WebSocketController {
    @MessageMapping("/sayHello" )
    @SendTo("/broker/hello")
    public String sayHello(String name) {
        return "Hello "+name;
    }    
}

Client Side (Javascript)

Import libraries

<script src="webjars/<wj:locate path="sockjs.min.js" />"></script>
<script src="webjars/<wj:locate path="stomp.min.js" />"></script>

Connect

var socket = new SockJS('/connect');
stompClient = Stomp.over(socket);
 
stompClient.connect({}, function(frame) {
  console.log('Connected: ' + frame);
  stompClient.subscribe('/broker/hello', function(message){
                	console.log(message);
  });
});

Send message

stompClient.send("/socket/sayHello", {}, "John Doe");

Disconnect

stompClient.disconnect();
console.log("Disconnected");

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub