一、前言
文本源自 微博客 且已获授权,请尊重版权。
《通义千问AI落地——下篇》如约而至。Websocket在这一类引用中,起到前后端通信的作用。因此,本文将介绍websocket在这类应用场景下的配置、使用、注意事项以及ws连接升级为wss连接
等;如下图,本站已经使用了wss连接:
二、后端接口
后端接口主要涉及Websocket的配置、握手认证、消息收发等,我们来逐一讲解:
2.1、WebSocket配置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;@EnableWebSocketMessageBroker
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {private TaskScheduler messageBrokerTaskScheduler;@Autowiredpublic void setMessageBrokerTaskScheduler(@Lazy TaskScheduler taskScheduler) {this.messageBrokerTaskScheduler = taskScheduler;}@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {// 指定允许握手的域名//String[] allowedOrigins = {"www.microblog.store", "xxx"};registry.addEndpoint("/ws/handshake").setAllowedOrigins("*") //如果指定握手域名,可以填入allowedOrigins .setHandshakeHandler(new UserHandshakeHandler());}@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {registry.setApplicationDestinationPrefixes("/ws").setUserDestinationPrefix("/user")// 客户端订阅消息的请求前缀,topic一般用于广播推送,queue用于点对点推送.enableSimpleBroker("/broad",</