Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

java - How to combine Spring REST and WebSocket?

I'm new to Spring and working on a university project.

The goal: Have a REST POST endpoint that saves data, but also sends a broadcast message using websocket.

Now, my RestController seems to be working fine, but dont really know how to implement the websocket part?

Here is how the endpoint looks like:

@PostMapping("/employees")
 Employee newEmployee(@RequestBody Employee newEmployee) {
    return repository.save(newEmployee);
 }

My previous ideas:

-Create a @Controller with a method that has @SendTo annotation?

-Can I use the @SendTo on the RestController newEmployee method?

What is the most efficient way?

question from:https://stackoverflow.com/questions/65891650/how-to-combine-spring-rest-and-websocket

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just like spring provides @RestController, it also provides @EnableWebSocket annotation and ways to handle bi-direction communication, below is the step by step method to create websocket connection in spring
First make a configuration class for making our WebSocketConnection class bean which will be handler for websocket connection, disconnection and message from client and add it to the WebSocketHandlerRegister with it's namespace.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {

    @Bean
    public WebSocketConnection getWebSocketConnection() {
        return new WebSocketConnection();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(getWebSocketConnection(), "/websocket");
    }
}

Now let us make our WebSocketConnection class

public class WebSocketConnection  extends TextWebSocketHandler {

    private static final Logger log = LoggerFactory.getLogger(WebSocketConnection.class);

    private static final Gson gson = new GsonBuilder().create();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("connected with the websocket client : " + session.getId());
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JsonObject parsedMessage = gson.fromJson(message.getPayload(), JsonObject.class);

        log.info("The message got from the client is " + parsedMessage);

        JsonObject responseMessage = new JsonObject();
        responseMessage.addProperty("response", "Your response was recorded by the server");
        responseMessage.addProperty("messageReceivedtime", LocalDateTime.now().toLocalDate().toString());
        int max = 100;
        int min = 20;
        responseMessage.addProperty("randomNo", (int) Math.floor(Math.random() * (max - min + 1) + min));

        session.sendMessage(new TextMessage(responseMessage.toString())); //sending message back to the client
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("connection closed from the websocket client : " + session.getId());
    }
}

and you are done here.
now from client side in javascript, you will have to make websocket client object like below

const webSocketClient = new WebSocket('ws://localhost:port/websocket');
//const webSocketClient = new WebSocket('wss://ip:port/websocket') for cases of secure connection

for more info about WebSocket client in javascript, please refer to this
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications

you mentioned your goal i.e 'Have a REST POST endpoint that saves data, but also sends a broadcast message using websocket' should not be in 1 go. what you can do is that when user saves the data, you can return the response from the server to the user whose data has been saved, then let that user send message to the websocket server which websocket server will broadcast to other users.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...