How can SpringBoot achieve point-to-point messaging?

In Spring Boot, you can use WebSocket to send messages between two points. WebSocket is a protocol that allows full-duplex communication over a single TCP connection, enabling a persistent connection between a web browser and server for the server to push data actively to the client.

Here are the steps to implement point-to-point messaging using Spring Boot:

  1. pom.xml file
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  1. Create a WebSocket configuration class: establish a configuration class to set up WebSocket related information. An example code is shown below:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
    }
}

In the example code above, WebSocketHandler() is a custom WebSocket handler, and /ws is the endpoint path for WebSocket.

  1. Create a WebSocket handler: Create a custom WebSocket handler to handle the establishment, closure, and sending of messages for WebSocket connections. Example code is provided below:
public class WebSocketHandler extends TextWebSocketHandler {

    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理收到的消息
        for (WebSocketSession s : sessions) {
            s.sendMessage(message);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }
}

In the sample code above, the afterConnectionEstablished() method is called when the WebSocket connection is established, the handleTextMessage() method is used to handle received text messages, and the afterConnectionClosed() method is called when the WebSocket connection is closed.

  1. Create a Controller class: Generate a Controller class to manage WebSocket-related requests. Sample code is provided below:
@RestController
@RequestMapping("/api")
public class MessageController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @PostMapping("/send/{userId}")
    public void sendMessage(@PathVariable("userId") String userId, @RequestBody String message) {
        messagingTemplate.convertAndSendToUser(userId, "/ws", message);
    }
}

In the example code above, the method sendMessage() is used to send messages to a specified WebSocket connection.

With this, the implementation of sending messages point-to-point is complete. You can send a message by sending a POST request to /api/send/{userId}, passing userId and message parameters.

Please note that the above example only demonstrates the basic implementation of sending messages point-to-point. In actual applications, you may need to further develop and optimize based on specific requirements.

bannerAds