最近有个需求是后端主动推送消息给前端,通过一番艰难险阻总算是给完成了,选择使用的是websocket,可以前后端进行通信
1、框架:
后端:springboot2.x
前端:vue2.x
2、原理:
后端建立一个websocket服务器,提供一个url,前端通过url与后端websocket服务器进行连接
3、使用的依赖:
在WebSocketConfig中会用到
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
4、websocket配置:
WebSocketConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}