在之前的项目中使用过H5的websocket,但是在移植到Springboot项目中时,发现和之前的用法有略微差别,主要是
在@ServerEndpoint管理分配上。
一、在非Springboot项目里,使用websocket要在pom文件中引入javaee标准
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
websocket服务器端直接添加@ServerEndpoint注解声明,然后保证前端websocke路径一致即可
@ServerEndpoint("/websocket}")
public class WebSocketServer {
...
}
二、而在Springboot项目中,就不需要引入javaee-api了,spring-boot已经包含了。
使用springboot的websocket功能:
1、首先引入springboot组件。
2、注入ServerEndpointExporter
注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。
要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,
因为它将由容器自己提供和管理。
3、websocket的具体实现类
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
...
}
使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。
虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
4、前端代码保证websocket地址一致
websocket = new WebSocket("ws://localhost:8080/websocket/{username}");
转自:https://blog.csdn.net/u011144425/article/details/79231212?utm_source=blogxgwz3
【参考】:
http://www.cnblogs.com/xdp-gacl/p/5193279.html Java后端WebSocket的Tomcat实现
http://blog.fens.me/java-websocket-intro/ Java现实WebSocket
http://tomcat.apache.org/tomcat-7.0-doc/web-socket-howto.html tomcat7 web socket
http://tomcat.apache.org/tomcat-8.0-doc/web-socket-howto.html tomcat8 web socket
https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket WebSocket对象api
https://www.zhihu.com/question/20215561 WebSocket 是什么原理?为什么可以实现持久连接?
https://www.nginx.com/blog/websocket-nginx/ NGINX as a WebSocket Proxy