赞
踩
WebSocket 是一种全新的协议。它将 TCP 的 Socket(套接字)应用在了web page上,从而使通信双方建立起一个保持在活动状态的连接通道,并且属于全双工通信(双方同时进行双向通信)。
WebSocket 的最大特点是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术的一种。
其他特点包括:
目前,很多网站都使用 Ajax 轮询方式来实现消息推送。
轮询是指在特定的的时间间隔(如每秒),由浏览器对服务器发出 HTTP 请求,然后由服务器返回最新的数据给客户端的浏览器。
这种传统的模式带来了很明显的缺点,即浏览器需要不断地向服务器发出请求,然而 HTTP 请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,会浪费很多的带宽资源。
而 WebSocket 允许服务端主动向客户端推送数据,这就使得客户端和服务器之间的数据交换变得更加简单。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
项目整体结构如图:
实现步骤
添加需要的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- webSocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- hutool --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.2.5</version> </dependency> <!-- thymeleaf--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
前端使用了 thymeleaf 模板引擎,需要在配置文件 application.yml 中对 thymeleaf 进行配置 :
# thymeleaf
spring:
thymeleaf:
check-template-location: true
suffix: .html
encoding: UTF-8
servlet:
content-type: text/html
mode: HTML5
cache: false
server:
port: 9999
在 WebsocketApplication 中继承 SpringBootServletInitializer,重写 configure 方法:
package com.test.websocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class WebsocketApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(WebsocketApplication.class); } public static void main(String[] args) { SpringApplication.run(WebsocketApplication.class, args); } }
新建配置类 WebSocketConfig,开启 WebSocket 支持
package com.test.websocket.config;
/**
* @author: jichunyang
**/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。