Vue+Websocket 带参数使用
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
免费下载资源
·
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;
}
}
GitHub 加速计划 / vu / vue
207.52 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 3 个月前
e428d891
Updated Browser Compatibility reference. The previous currently returns HTTP 404. 3 个月前
更多推荐
已为社区贡献1条内容
所有评论(0)