在手机上相信都有来自服务器的推送消息,比如一些及时的新闻信息,这篇文章主要就是实现这个功能,只演示一个基本的案例。使用的是websocket技术。
WebSocket协议是基于TCP的一种新的网络协议。它实现了客户端与服务器全双工通信,学过计算机网络都知道,既然是全双工,就说明了服务器可以主动发送信息给客户端。这与我们的推送技术或者是多人在线聊天的功能不谋而合。
为什么不使用HTTP 协议呢?这是因为HTTP是单工通信,通信只能由客户端发起,客户端请求一下,服务器处理一下,这就太麻烦了。于是websocket应运而生。
下面我们就直接开始使用Springboot开始整合。以下案例都在我自己的电脑上测试成功,你可以根据自己的功能进行修改即可。
1.添加依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
2.新建config包,创建WebSocketConfig类
- @Configuration
- public class WebSocketConfig {
- @Bean
- public ServerEndpointExporter serverEndpointExporter(){
- return new ServerEndpointExporter ();
- }
- }
3.新建service包,创建WebSocketServer类
- @Component
- @ServerEndpoint("/webSocket")
- @Slf4j
- public class WebSocket {
- //与某个客户端的连接会话,需要通过它来给客户端发送数据
- private Session session;
- //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
- private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
-
- /**
- * 连接建立成功调用的方法
- */
- @OnOpen
- public void onOpen(Session session){
- this.session=session;
- webSocketSet.add(this); //加入set中
- log.info("【WebSocket消息】有新的连接,总数:{}",webSocketSet.size());
- }
-
- /**
- * 连接关闭调用的方法
- */
- @OnClose
- public void onClose(){
- webSocketSet.remove(this);//从set中删除
- log.info("【WebSocket消息】连接断开,总数:{}",webSocketSet.size());
- }
-
- /**
- * 收到客户端消息后调用的方法
- * @param message 客户端发送过来的消息
- */
- @OnMessage
- public void onMessage(String message ){
- log.info("【WebSocket消息】收到客户端发来的消息:{}",message);
- }
-
- public void sendMessage(String message){
- for (WebSocket webSocket:webSocketSet) {
- log.info("【webSocket消息】广播消息,message={}",message);
- try {
- webSocket.session.getBasicRemote ().sendText(message);
- } catch (Exception e) {
- e.printStackTrace ();
- }
- }
- }
- }
4.在前端js里面加入接受后端向前端主动推送的消息
- var webSocket = null;
- if('WebSocket' in window){
- webSocket = new WebSocket('ws://localhost:8081/webSocket')
- }else {
- alert('该游览器不支持webSocket!')
- }
- webSocket.onopen =function (event) {
- console.log('建立连接');
- }
- webSocket.onclose = function (event) {
- console.log("连接关闭");
- }
- webSocket.onmessage = function (event) {
- console.log('收到消息'+event.data)
- //单窗提醒,播放音乐
- $('#myModal').modal('show');
- }
- webSocket.onerror = function () {
- alert('webSocket通信发生错误!')
- }
- window.onbeforeunload = function () {
- webSocket.close();
- }
5.测试:在添加营销机会Service层引入,发送webSocket消息
- //发送webSocket消息
- webSocket.sendMessage ("你有新的营销用户加入:" + saleChance.getLinkMan ());
6.接口测试

7. 这时后端向前端主动推送消息,前端也收到后端发送的消息通知。

案例Springboot+Webebsocket整合到此结束,谢谢观看。