Vue+Websocket 带参数使用
在页面初始化的时候就建立Websocket
vue 前台
在这里插入图片描述

1.在data(){定义websocket=null}
2.在methods(){}以下方法

 //打开一个websocket
        webSocket() {
             const wsurl = localhost:端口号 + "/deviceMonitorWebSocket/" + _self.userId +"/"+deviceId;
            _self.websocket = new WebSocket(wsurl);
            _self.websocket.onopen = _self.websocketonopen;
            _self.websocket.onmessage = _self.websocketonmessage;
            _self.websocket.onerror = _self.websocketonerror;
            _self.websocket.onclose = _self.websocketclose;
        },
        //连接建立之后执行send方法发送数据
        websocketonopen() {
            console.log("Connected to WebSocket server.");
        },
        //连接建立失败重连
        websocketonerror() {
            console.log("Connected to WebSocket server error");
        },
        //数据接收
        websocketonmessage(e) {//e为websocket里面的值
            if (e.data != null && e.data != undefined) {
                let tmp_data = JSON.parse(e.data)
                var productInfoList = tmp_data.devicesList;  
                    Vue.set(this, 'productList', productInfoList);//'productList'为你页面上需要websocket的值
            }
        },
        //关闭
        websocketclose(e) {
            console.log('websocket Connection Closed. ');
        },

关掉timerTask

destroyed() {
        _self.websocket.close();
    },
 

java 后台
DeviceMonitorWebSocket类

@Component
//此注解相当于设置访问URL
@ServerEndpoint("/deviceMonitorWebSocket/{id}/{productId}")
public class DeviceMonitorWebSocket {

    private static CopyOnWriteArraySet<DeviceMonitorWebSocket> webSockets = new CopyOnWriteArraySet<DeviceMonitorWebSocket>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();
    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id, @PathParam(value = "productId") String productId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(id, session);

        DeviceTask deviceTask = DeviceTask.getInstance(id, productId);
        deviceTask.start();

    }
    
    /**
    *
    * @param session
    * @param error
    */
   @OnError
   public void onError(Session session, Throwable error) {
       error.printStackTrace();
   }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        DeviceTask.getInstance("", "").destroyed();
    }

    @OnMessage
    public void onMessage(String message) {
        //JSONObject jsonObject =JSONObject.parseObject(message);

    }

    /**
     * 此为广播消息
     *
     * @param message
     */
    public void sendAllMessage(String message) {
        for (DeviceMonitorWebSocket webSocket : webSockets) {
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息 (发送文本)
     *
     * @param id
     * @param message
     */
    public void sendTextMessage(String id, String message) {
        Session session = sessionPool.get(id);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息 (发送对象)
     *
     * @param id
     * @param message
     */
    public void sendObjMessage(String id, Object message) {
        Session session = sessionPool.get(id);
        if (session != null) {
            try {
//              session.getAsyncRemote().sendObject(message);
            	session.getBasicRemote().sendText(JSONObject.toJSONString(message));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

定时器任务DeviceTask

public class DeviceTask extends TimerTask {
    private DeviceMonitorWebSocket deviceMonitorWebSocket = new DeviceMonitorWebSocket();
    private SysStatusService sysStatusService =(SysStatusService) ApplicationContextUtils.getBeanById("SysStatusService");
    private static DeviceTask deviceTask = null;
    private Timer timer = null;
    private String userId;
    private String productId;
    public DeviceTask() {
    }



    //单例模式,保持这个对象
    public static DeviceTask getInstance(String userId, String productId) {
        if  (deviceTask == null) {
            //当flag == true时,为了解决,timer.cancel()后,重新创建一个timer
            deviceTask= new DeviceTask();

        }
        deviceTask.setUserId(userId);
        deviceTask.setProductId(productId);
        return deviceTask;
    }

    public void start() {
        if (timer == null) {
            timer = new Timer();
        } else {
            //从此计时器的任务队列中移除所有已取消的任务。
           timer.purge();
        }

        // myTimeTask 指定执行的线程 delay 延迟时间 timestamp 指定每格多久再次执行一次( 5min执行一次)
        timer.scheduleAtFixedRate(this,0, 定时的时间);
    }

    //定时执行的方法
    @Override
    public void run() {
       //你需要websocket获取的什么数据
         Map<String,Object> deviceMap =*****Service.方法(productId);
        deviceMonitorWebSocket.sendObjMessage(userId,deviceMap);

    }

    public void destroyed() {
        //终止此计时器,丢弃所有当前已安排的任务。(不但结束当前schedule,连整个Timer的线程(即当前的定时任务)都会结束掉)
        deviceTask.cancel();
        deviceTask=null;
        timer.cancel();
        timer.purge();
        timer=null;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }
}

Logo

前往低代码交流专区

更多推荐