WebSocket 在springboot中使用

在之前的项目中使用过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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值