DEV Community

saif ali
saif ali

Posted on

Socket Programming in Spring boot

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

Enter fullscreen mode Exit fullscreen mode

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";
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
        }
    });
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Response

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

Enter fullscreen mode Exit fullscreen mode

That's it. your socket programming is ready.

Top comments (0)