Spring Boot整合WebSocket实现实时通信,前端实时通信,前后端实时通信
以下是一个使用Spring Boot整合WebSocket的简单示例,实现了前后端实时通信的功能。
后端代码(Spring Boot):
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.*;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@GetMapping("/")
@ResponseBody
public String home() {
return "Welcome to WebSocket Chat!";
}
}
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class WebSocketController {
@MessageMapping("/chat.sendMessage")
@SendTo("/topic/public")
public ChatMessage sendMessage(ChatMessage message) {
return message;
}
}
class ChatMessage {
private String content;
// getters and setters
}
前端代码(HTML + JavaScript):
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.7.0/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/stomp.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
</head>
<body>
<div>
<input type="text" id="name" placeholder="Your Name" />
<button id="connect">Connect</button>
<button id="disconnect">Disconnect</button>
<input type="text" id="message" placeholder="Message" />
<button id="send">Send Message</button>
<div id="conversationDiv">
<label for="conversation">Conversation:</label>
<textarea id="conversation" rows="4" cols="50"></textarea>
</div>
</div>
<script>
var stompClient = null;
$('#con
评论已关闭