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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…