SpringBoot使用WebSocket
    		       		warning:
    		            这篇文章距离上次修改已过416天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中使用WebSocket可以通过Spring的WebSocket支持来实现。以下是一个简单的例子,展示了如何在Spring Boot应用程序中设置WebSocket端点。
- 添加依赖到你的pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>- 配置WebSocket:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
 
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}- 创建WebSocket控制器:
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
 
@Controller
public class WebSocketController {
 
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String greeting(String message) {
        return "Hello, " + message + "!";
    }
}- 前端使用WebSocket的例子(使用JavaScript和SockJS客户端):
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.7.0/dist/sockjs.min.js"></script>
<script>
    var socket = new SockJS('/ws');
    var stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function(greeting){
            console.log(greeting.body);
        });
    });
    
    function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send("/app/hello", {}, name);
    }
</script>
 
<input type="text" id="name" />
<button onclick="sendName()">Send</button>这个例子展示了如何在Spring Boot应用程序中设置WebSocket端点,并使用SockJS和STOMP协议与客户端进行通信。在前端,用户可以在文本框输入名字,点击发送按钮,将消息发送到后端,后端处理这个消息并通过WebSocket发送回客户端。
评论已关闭