loading...

Socket Programming in Spring boot

saifali40 profile image saif ali ・2 min read

Spring Boot can make standalone applications easily you need to run either clicking on the build or running using Java -jar command in your terminal. spring boot comes with a lot of awesome dependencies. I would say my favorite one is WebSocket it reduces your work a lot and no need to use an API to fit the same requirement, it is fast and effective. You just need to do the following things to your project and you can avoid using API for real-time messaging or pub-sub.

add the following code to your gradle

compile("org.springframework.boot:spring-boot-starter-websocket")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")

these are the essential dependencies for the socket programming in the spring-boot application, your environment is set ready to do coding now.

Example Configuration

@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

    @Override
    void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").withSockJS()
    }
}

To the People who are thinking why I'm not using ";" in my code. I hate ";" so I'm not using it and It is not the real answer I'm using groovy for this example.

Now let's look into the Controller

@Controller // of course you need this 
class SocketController {
    @MessageMapping("/request")
    @SendTo("/response")
    def test() throws Exception {
        return "Hello world";
    }
}

You have done your pub-sub backend process let's go for front end
add these two scripts to your page

<script src="${pageContext.request.contextPath}/webjars/sockjs-client/1.0.2/sockjs.min.js"></script>
<script src="${pageContext.request.contextPath}/webjars/stomp-websocket/2.3.3/stomp.min.js"></script>

add the following code to document ready function ()

var stompClient = null;

    $(function () {
        function connect() {
            var socket = new SockJS('/gs-guide-websocket');
            stompClient = Stomp.over(socket);
        }
    });

Place this code where your current control is if you are using angular please add this within the scope so you will be able to use the scope for immediate update

Sending function

stompClient.send("/socket/request/");//add client desitinationprefix 

Response

stompClient.connect({}, function (frame) {
        stompClient.subscribe('/response/', function (reponse) {
              console.log(reponse);
        });
});

That's it. your socket programming is ready.

Posted on by:

Discussion

markdown guide