用websocket实现后台推送消息

Posted 戈博小刀

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用websocket实现后台推送消息相关的知识,希望对你有一定的参考价值。

 

转:

1前台实现

技术图片
 1 connect:function() {
 2         var webSocketIP = window.CRM_CONFIG.WebSocketIP;
 3         var target  = ‘ws://‘+webSocketIP+‘/websocket‘;
 4         if (‘WebSocket‘ in window) {
 5             ws = new WebSocket(target);
 6         } else if (‘MozWebSocket‘ in window) {
 7             ws = new MozWebSocket(target);
 8         } else {
 9             return;
10         }
11         ws.onopen = function () {
12             console.log(‘Info: WebSocket connection opened.‘);
13             document.getElementById("wsMsg").style.display = "block";
14         };
15         var self = this;
16         ws.onmessage = function (event) {
17             if(‘您有如下工单需要及时处理:‘!= event.data) {
18                  self.setState({wsMessage: event.data})
19                  document.getElementById("wsMsg").style.display = "block";
20             }else{
21                  document.getElementById("wsMsg").style.display = "none";
22             }
23         };
24 
25    <div id="wsMsg" className="msgDialog msgDiv">
26                     <div className="msgContent"  ><a onClick ={this.closeMsg}> X&nbsp;</a></div>
27                     {this.state.wsMessage}
28                 </div>
技术图片

2、pom.xml依赖

技术图片
 1     <!--spring-websocket-->
 2         <dependency>
 3             <groupId>javax.servlet</groupId>
 4             <artifactId>javax.servlet-api</artifactId>
 5             <version>3.1.0</version>
 6         </dependency>
 7         <dependency>
 8             <groupId>org.springframework</groupId>
 9             <artifactId>spring-websocket</artifactId>
10             <version>${spring.version}</version>
11         </dependency>
技术图片

3、spring.xml配置

技术图片
 <!--websocket 配置-->
    <bean id="websocket" class="com.oasis.crm.controller.websocket.WebsocketEndPoint"/>
    <websocket:handlers  allowed-origins="*">
        <websocket:mapping path="/websocket" handler="websocket"/>
        <websocket:handshake-interceptors>
            <bean class="com.oasis.crm.controller.websocket.HandshakeInterceptor"/>
        </websocket:handshake-interceptors>
    </websocket:handlers>
技术图片

4、java代码

技术图片
package com.oasis.crm.controller.websocket;
import com.oasis.crm.dao.biz.user.UserDao;
import com.oasis.crm.model.biz.user.User;
import com.oasis.crm.service.biz.order.AcceptedWorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 推送即将要处理完成的受理单给处理人
 */
@RequestMapping("/websocket")
public class WebsocketEndPoint extends TextWebSocketHandler {

    @Autowired
    private AcceptedWorkOrderService acceptedWorkOrderService;

    @Autowired
    private UserDao userDao;

    private Timer timer;

    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage message) throws Exception {
        if(!session.isOpen()){
            timer.cancel();
            return;
        }
        super.handleTextMessage(session, message);
        session.sendMessage(message);
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String loginUserName = session.getPrincipal().getName();
        User user = userDao.findUserByLoginName(loginUserName);
        timer = new Timer(true);
        long delay = 0;
        OrderTimeTask orderTimeTask = new OrderTimeTask(user,session);
        timer.schedule(orderTimeTask,delay, 60000);// 设定指定的时间time,此处为1分钟
    }


    class OrderTimeTask extends TimerTask{
        private User user;
        private WebSocketSession session;

        public OrderTimeTask(User user,WebSocketSession session){
            this.user = user;
            this.session = session;
        }

        @Override
        public void run() {
            try {
                String reminder = acceptedWorkOrderService.getLastReminderOrder(user.getId());
                TextMessage textMessage = new TextMessage(reminder);
                handleMessage(session,textMessage);
            } catch (Exception e){
                e.printStackTrace();
            }

        }
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("Connection Closed!");
    }


}
技术图片
技术图片
package com.oasis.crm.controller.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;


public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
    
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Map<String, Object> attributes) throws Exception {
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
技术图片

================

或者前台拉定时取消息

技术图片
    setInterval(()=> {
            this.getReminders();
        }, 300000);

 getReminders(){
        $.getJSON(Remote.acceptedWorkOrder.reminderOrders,packVo=>{
            this.setState({
                wsMessage:packVo.vo
            });
        });
        if(‘您有如下工单需要及时处理:‘!= this.state.wsMessage&&‘‘!=this.state.wsMessage){
            document.getElementById("wsMsg").style.display = "block";
        }else{
            document.getElementById("wsMsg").style.display = "none";
        }
    }
技术图片

 

以上是关于用websocket实现后台推送消息的主要内容,如果未能解决你的问题,请参考以下文章

java实现后台服务器消息推送

SpringBoot 集成 WebSocket,实现后台向前端推送信息

SpringBoot 集成 WebSocket,实现后台向前端推送信息

SpringBoot 集成 WebSocket,实现后台向前端推送信息

SpringBoot 集成 WebSocket,实现后台向前端推送信息

Websocket web实时消息服务器后台推送技术方案---GoEasy