Spring boot部分
pom.xml引入依赖
<!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
新建配置类
package com.itms.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
新建websocket服务类
package com.nokia.itms.admin.runner;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.nokia.itms.admin.model.ModuleInformation;
import com.nokia.itms.admin.model.ServerModuleInfo;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/moduleInfoWSces")
public class SepWebSocketController {
//静态变量,用来记录当前在线连接数。设计为安全的
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<SepWebSocketController> webSocketSet = new CopyOnWriteArraySet<SepWebSocketController>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
public Session session;
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
while (true){
try {
Thread.sleep(20000);
sendMessage(this); //调用推送方法,进行数据推送
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void sendMessage(SepWebSocketController sepWebsocketController) {
//模拟数据
String receiveJsonData = "{" +
"\"IP\":\"135.251.218.88\",\n" +
"\"moduleInfo\":[\n" +
"{\n" +
"\"status\":\"running\",\n" +
"\"version\":\"1.0\",\n" +
"\"pid\":\"111\",\n" +
"\"module\":\"nbiproc\",\n" +
"\"service_name\":\"itms\"\n" +
"},\n" +
"{\n" +
"\"status\":\"stop\",\n" +
"\"version\":\"1.0\",\n" +
"\"pid\":\"888\",\n" +
"\"module\":\"nbitktws\",\n" +
"\"service_name\":\"itms_141\"\n" +
"},\n" +
"{\n" +
"\"status\":\"running\",\n" +
"\"version\":\"1.0\",\n" +
"\"pid\":\"112\",\n" +
"\"module\":\"report_1\",\n" +
"\"service_name\":\"itms\"\n" +
"},\n" +
"{\n" +
"\"status\":\"running\",\n" +
"\"version\":\"1.0\",\n" +
"\"pid\":\"113\",\n" +
"\"module\":\"report_2\",\n" +
"\"service_name\":\"itms\"\n" +
"}\n" +
"]\n" +
"}";
//将数据转换成前端需要的格式并返回
String jsonData = formatData(receiveJsonData);
//推送数据
sepWebsocketController.session.getAsyncRemote().sendText(jsonData);
}
@OnMessage
public void onMessage(String message) {
System.out.println("收到客户端消息:"+message);
}
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
SepWebSocketController.onlineCount++;
}
public static synchronized void subOnlineCount() {
SepWebSocketController.onlineCount--;
}
//模拟数据转换
private String formatData(String receiveJsonData) {
ServerModuleInfo serverModuleInfo = JSON.parseObject(receiveJsonData, new TypeReference<ServerModuleInfo>() {});
List<ModuleInformation> list =new ArrayList<>();
for (ModuleInformation svm: serverModuleInfo.getModuleInfo()) {
ModuleInformation mi = new ModuleInformation();
mi.setIp(serverModuleInfo.getIp());
mi.setModule(svm.getModule());
mi.setPid(svm.getPid());
mi.setVersion(svm.getVersion());
mi.setStatus(svm.getStatus());
mi.setServiceName(svm.getServiceName());
list.add(mi);
}
String jsonData = JSON.toJSONString(list);
return jsonData;
}
}
前端VUE
<template>
<div>
</div>
</template>
<script>
export default {
data() {
return {
websock: null
}
},
created() {
this.initWebSocket()
},
destroyed() {
this.websock.close() // 离开路由之后断开websocket连接
},
methods: {
initWebSocket() { // 初始化weosocket
const wsuri = 'ws://localhost:8080/itmsadmin/moduleInfoWSces'
this.websock = new WebSocket(wsuri)
this.websock.onmessage = this.websocketonmessage
this.websock.onopen = this.websocketonopen
this.websock.onerror = this.websocketonerror
this.websock.onclose = this.websocketclose
// this.websock.on('/topic/getModuleInfo', this.websock.onmessage)
},
websocketonopen() { // 连接建立之后执行send方法发送数据
const actions = { 'test': '12345' }
this.websocketsend(JSON.stringify(actions))
},
websocketonerror() { // 连接建立失败重连
this.initWebSocket()
},
websocketonmessage(e) { // 数据接收
const redata = JSON.parse(e.data)
console.log(redata)
},
websocketsend(Data) { // 数据发送
this.websock.send(Data)
},
websocketclose(e) { // 关闭
console.log('断开连接', e)
}
}
</script>
ok~