WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Framework · Expert · question 71 of 100

How can you handle WebSocket communication in a Spring application using Spring WebSocket?

📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

Spring WebSocket is a part of the Spring Framework that enables WebSocket communication between the client and the server. In order to handle WebSocket communication in a Spring application, we need to follow these steps:

1. Add the Spring WebSocket dependency to the project. This can be done by adding the following dependency to the projects pom.xml file:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>5.x.x</version>
</dependency>

2. Create a WebSocket configuration class. This class should extend the ‘AbstractWebSocketMessageBrokerConfigurer‘ class and override its ‘registerStompEndpoints()‘ method. This method is responsible for configuring the WebSocket endpoints that the clients can connect to. Heres an example of how a WebSocket configuration class can be set up:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }

}

This configuration sets up two message routes: ‘/topic‘ and ‘/app‘. The ‘/topic‘ route is used for broadcasting messages to all connected clients, while the ‘/app‘ route is used for sending messages to a specific client.

3. Handle WebSocket messages in controllers. In order to handle WebSocket messages, we need to use Springs WebSocketHandler methods. These methods are used for sending, receiving, and processing WebSocket messages. Heres an example of how a controller can be set up to handle incoming WebSocket messages:

@Controller
public class WebSocketController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + message.getName() + "!");
    }

}

This controller handles incoming messages on the ‘/hello‘ route and sends a response message to the ‘/topic/greetings‘ route.

4. Connect to the WebSocket endpoint from a client. Once the WebSocket endpoint has been set up and the messages have been handled in the controller, we can connect to the endpoint from a client. This can be done using a WebSocket client library or by using the built-in JavaScript library. Heres an example of how a client can connect to the endpoint using JavaScript:

var socket = new SockJS('/websocket');
var stompClient = Stomp.over(socket);

stompClient.connect({}, function(frame) {
    stompClient.subscribe('/topic/greetings', function(greeting) {
        var body = JSON.parse(greeting.body);
        alert(body.content);
    });
});

function sendGreeting() {
    var name = $('#name').val();
    stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}

This JavaScript code creates a SockJS instance and connects to the ‘/websocket‘ endpoint. Once the connection is established, it subscribes to the ‘/topic/greetings‘ route and listens for messages. The ‘sendGreeting()‘ function sends a message to the ‘/app/hello‘ route when the button is clicked.

These are the basic steps required for handling WebSocket communication in a Spring application using Spring WebSocket. With this setup, we can create real-time applications that can handle user interactions in a seamless, responsive, and efficient way.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Framework interview — then scores it.
📞 Practice Spring Framework — free 15 min
📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

All 100 Spring Framework questions · All topics