在Java中,使用WebSocket處理消息確認的方法如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketConfig
,并繼承AbstractWebSocketMessageBrokerConfigurer
。在這個類中,你需要配置WebSocket的端點和消息代理:@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-demo").withSockJS();
}
}
MessageController
,用于處理客戶端發送的消息和廣播消息給其他客戶端:@Controller
public class MessageController {
@MessageMapping("/send")
@SendTo("/topic/messages")
public String sendMessage(@Payload String message) {
return "Received message: " + message;
}
}
// 連接到WebSocket服務器
var socket = new SockJS('/websocket-demo');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
// 發送消息
stompClient.send("/app/send", {}, JSON.stringify({ content: 'Hello, WebSocket!' }));
});
// 監聽服務器發送的消息
stompClient.subscribe('/topic/messages', function (response) {
console.log('Received message: ' + response.body);
});
在客戶端,你可以在接收到服務器發送的消息后設置確認標志:
stompClient.subscribe('/topic/messages', function (response) {
console.log('Received message: ' + response.body);
// 設置確認標志
var message = JSON.parse(response.body);
message.ack = true;
stompClient.send("/app/confirm", {}, JSON.stringify(message));
});
在服務器端,你可以創建一個MessageConfirmListener
類來處理確認消息:
public class MessageConfirmListener implements StompFrameHandler {
@Override
public void handleFrame(StompFrame frame) {
if (frame.getHeaders().get("ack") != null && "true".equals(frame.getHeaders().get("ack"))) {
// 消息已確認,執行相應操作
System.out.println("Message confirmed: " + frame.getPayload());
}
}
}
最后,將MessageConfirmListener
添加到WebSocket控制器中:
@Controller
public class MessageController {
@MessageMapping("/send")
@SendTo("/topic/messages")
public String sendMessage(@Payload String message, SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("messageId", message);
return "Sent message: " + message;
}
@MessageMapping("/confirm")
public void confirmMessage(@Payload String message, SimpMessageHeaderAccessor headerAccessor) {
String messageId = (String) headerAccessor.getSessionAttributes().get("messageId");
if (messageId != null) {
// 消息已確認,執行相應操作
System.out.println("Message confirmed: " + messageId);
}
}
}
這樣,你就可以使用WebSocket在Java中處理消息確認了。