用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";
        }
    }

 

posted @ 2016-06-17 18:12  挖坑大王  阅读(44641)  评论(12编辑  收藏  举报