![0d0c815d005ac89bd8cc2ac1eeab53ea.png](https://i-blog.csdnimg.cn/blog_migrate/9a5d396159399bcbb5978df58b967ec8.jpeg)
本文章利用一个小的对话demo来展示springboot+websocket的实现。
下面开始简单的实现过程:
我的项目结构:
![aba4838663d65026647eff7521affb5a.png](https://i-blog.csdnimg.cn/blog_migrate/dcacd461f93819338b92402f92bc56a2.png)
一、首先,创建springboot项目,在pox.xml中加入(下面是我的pom.xml的dependencies里的全部依赖,因为,这个是最简单的入门例子,所以只有主要的websocket和web依赖)
![96e73e28bd17e5ad3d82b7e75345e4ca.png](https://i-blog.csdnimg.cn/blog_migrate/c04f76ad34ecb33006b5345e5939b357.jpeg)
二、创建一个页面index.html,前端跳转后端的一些必要代码
![207304683a6832e4e3dfb85b8b7fddfe.png](https://i-blog.csdnimg.cn/blog_migrate/4a3f1de3cbdb8660d36f659c85756dc1.jpeg)
三、后端的socket处理
![173079d05896f1d9713a6225ba83faff.png](https://i-blog.csdnimg.cn/blog_migrate/ef8c13226ce561f103e9c6731bc12a71.jpeg)
![03be6d882a3c03445b6d065927fd99f4.png](https://i-blog.csdnimg.cn/blog_migrate/118fd0c8253497cc6f544da834d98e65.jpeg)
四、springboot要注入ServerEndpointExporter
注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。 要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter, 因为它将由容器自己提供和管理。
WebSocketConfig.java
![8977be99a1f8685a183f0a8f9ea37630.png](https://i-blog.csdnimg.cn/blog_migrate/d2eb397880b0a50dc8badf1cc96f02f2.jpeg)
使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
全部的代码就是这样,没有其他的配置,都在这儿了。完成代码后,打开两个浏览器,可以看到两个页面可以实现即时通讯的功能。(如下图效果!)
![1c5ac63647f3e94394d15d012af28129.png](https://i-blog.csdnimg.cn/blog_migrate/6e87d9cdf59aa144ba3b60af1a80dcc9.jpeg)
我这些内容也是看了好几篇博客,现在写出来记在自己的小本本上,免得下次还得搜其他人的
原作者姓名:Le.Hao
原出处:CSDN
原文链接:springboot+websocket的实现_Le.Hao的博客-CSDN博客