#工作#

以下代码根据需要自行优化

一、后端接口

1.引入jar包

javax.websocket

javax.websocket-api

1.1

provided

2.创建后端WebSocketController类

package com.idata.web.controller;

/*自行引入包*/

/**

* @ClassName WebSocketController

* @Create 2019-07-15 17:51

*/

@ServerEndpoint("/websocket/{site_id}/{type}")

public class WebSocketController extends BaseController implements Runnable{

private static Logger logger = LoggerFactory.getLogger(WebSocketController.class);

public static Map> webSocketSet = new HashMap>();

private Session session;

//保存每一个Session的 site_id

private String Site_id;

private String type;

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

public String getSite_id() {

return Site_id;

}

public void setSite_id(String site_id) {

Site_id = site_id;

}

int i=0;

public void run() {

System.out.println("每分钟执行一次");

try{

// 推送监测数据

pushMessage();

}catch (Exception e){

e.printStackTrace();

}

}

//推送数据方法,里面业务逻辑自行填写

public void pushMessage()throws IOException, EncodeException{

//服务器主动推送

System.out.println("推送开始。。。。");

//自定义json个数数据,模拟接收到前台的json数据

String jsonStr = "{\"name\":\"张三\",\"age\":\"23\"}";

JSONObject jsonObj = JSONObject.fromObject(jsonStr);

webSocketSet.forEach((k, v) ->{

v.forEach(socket ->{

//推送数据

socket.session.getAsyncRemote().sendObject(jsonObj);

socket.session.getAsyncRemote().sendText("测试数据。。。");

});

});

}

}

3.配置定时器定时执行推送数据

二、前端代码

1.静态文件中写入后端url

2.vue文件中 data创建常量

3.创建sock方法

sock () {

const _this = this

var websocket = null

websocket = new WebSocket(config.url + this.site_id + '/' + '2')

this.websocket = websocket

//连接发生错误的回调方法

websocket.onerror = function () {

}

//连接成功建立的回调方法

websocket.onopen = function (event) {

console.log('webSocket连接成功。。')

}

//接收到消息的回调方法

websocket.onmessage = function (event) {

console.log('data',event)

}

//连接关闭的回调方法

websocket.onclose = function () {

}

//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。

window.onbeforeunload = function () {

closeWebSocket()

}

//关闭WebSocket连接

function closeWebSocket () {

console.log('webSocket关闭。。')

websocket.close()

}

//发送消息

},

3.建立连接

3.关闭会话时 关闭连接

精彩文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: