springboot vue websocket
文档:springboot vue websocket.note
链接:http://note.youdao.com/noteshare?id=4e05bf64a69dbd7d599625b916a41778&sub=8EE53268F7DC4779ACCB6073367EAD25
添加链接描述
package com.starp.exam.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.starp.util.JsonUtil;
import top.starp.util.ReturnT;
import top.starp.util.StringUtils;
import javax.websocket.OnOpen;
//@OnOpen
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 新订单推送socket
*
* @author: pansong
* @date: 2020-06-01 11:25
**/
@Slf4j
//@ServerEndpoint("/webSocket/addOrder/{userId}")
@ServerEndpoint("/webSocket/{userId}")
//@ServerEndpoint("/webSocket")
@Component
//WebSocketServer.java
@Data
public class WebSocketServer {
/**
* session 与客户端的连接对话,需要通过其给客户端发送消息
* userId 用户唯一标识
* webSocketMap 存放已连接的客户端信息——ConcurrentHashMap是线程安全的
*/
private Session session;
private String userId;
private static ConcurrentMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
WebSocketServerListener webSocketServerListener;
/***
* 连接建立
*
* @param session 客户端对话
* @param userId 用户id
* @return: void
* @author: pansong
* @date: 2020/6/11 23:45
**/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
webSocketMap.put(userId, this);
log.info(userId + ":连接,在线人数:" + webSocketMap.size());
this.sendMsg("pong");
if(webSocketServerListener!=null){
webSocketServerListener.onOpen(session,userId);
}
// webSocketServerListener.onOpen(session,userId);
}
/***
* 连接关闭
*
* @param
* @return: void
* @author: pansong
* @date: 2020/6/11 23:45
**/
@OnClose
public void onClose() {
if (this.userId != null && webSocketMap.containsKey(this.userId)) {
webSocketMap.remove(this.userId);
}
log.info(this.userId + ":退出,在线人数:" + webSocketMap.size());
if(webSocketServerListener!=null){
webSocketServerListener.onClose();
}
// EquipmentRepository equipmentRepository=
// WebSocketDbService.webSocketDbService.equipmentRepository;
// Equipment byDeviceId = equipmentRepository.findByDeviceId(this.userId);
byDeviceId.setStatus("退出");
// byDeviceId.setStatus("离线");
byDeviceId.setStatus(EquipStatus.);
// log.info("byDeviceId 设置退出之后 {}",byDeviceId);
// Equipment save = WebSocketDbService.
// webSocketDbService.equipmentRepository.save(byDeviceId);
}
// @Resource
// ScreenshotLogRepository screenshotLogRepository;
/***
* 连接出错
*
* @param throwable
* @return: void
* @author: pansong
* @date: 2020/6/11 23:46
**/
@OnError
public void onError(Throwable throwable) {
log.error(this.userId + ":错误,原因:" + throwable.getMessage());
if (webSocketMap.containsKey(this.userId)) {
webSocketMap.remove(this.userId);
}
if(webSocketServerListener!=null){
webSocketServerListener.onError(throwable);
}
}
/***
* 推送消息到前端
*
* @param msg 消息内容
* @return: void
* @author: pansong
* @date: 2020/6/11 23:46
**/
public Boolean sendMsg(String msg) {
try {
this.session.getBasicRemote().sendText(msg);
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
static String screenshot = "screenshot";
/**
* let data = {
* msg:"status",
* deviceid:state.deviceId,
* state: state.wsStatus
* }
*/
static String status = "status";
/**
* 设备状态
*
* @param jsonObject
*/
void onStatusChangeMsg(JSONObject jsonObject) {
log.info("onStatusChangeMsg jsonObject {}",jsonObject);
// String deviceid = jsonObject.getString("deviceid");
// log.info("deviceid {}",deviceid);
// Equipment byDeviceId = WebSocketDbService.
// webSocketDbService.equipmentRepository.findByDeviceId(deviceid);
// log.info("byDeviceId {}",byDeviceId);
// String state = jsonObject.getString("state");
// log.info("state {}",state);
// byDeviceId.setStatus(state);
// EquipmentRepository equipmentRepository = WebSocketDbService.
// webSocketDbService.equipmentRepository;
// Equipment save = equipmentRepository.save(byDeviceId);
ws:localho/websocket/{vmc
// log.info("save {}",save);
}
/**
* 之后管理前端请求 给我
* 我拿出 最新的 照片
*
* @param jsonObject
*/
// void onScreenshotMsg(JSONObject jsonObject) {
JsonUtil.getJsonSchema()
JsonUtil.stringToObject()
JsonUtil.strToObj()
ScreenshotLog screenshotLog = JsonUtil.jsonObjToJavaClass(jsonObject,
ScreenshotLog.class);
// log.info("jsonObject {}", jsonObject);
// ScreenshotLog screenshotLog = new ScreenshotLog();
// screenshotLog.fromJsonObject(jsonObject);
jsonObject.getString("")
// log.info("screenshotLog {}", screenshotLog);
//
//
// ScreenshotLogRepository screenshotLogRepository =
// WebSocketDbService.webSocketDbService.screenshotLogRepository;
//
// log.info("screenshotLogRepository {}", screenshotLogRepository);
// if (screenshotLogRepository == null) {
// log.info("screenshotLogRepository 是null ");
// return;
// }
//
// log.info("screenshotLog {}", screenshotLog);
// screenshotLog.setCreateTime(new Date());
ScreenshotLog screenshotLog = jsonObject.toJavaObject(ScreenshotLog.class);
// ScreenshotLog save = screenshotLogRepository.save(screenshotLog);
// log.info("save {}", save);
//
// }
/**
* 收到消息
*
* @param msg 消息内容
* @return: void
* @author: pansong
* @date: 2020/6/11 23:48
**/
@OnMessage
public void onMessage(String msg) {
log.info("msg {}", msg);
// StringUtils.isNotBlank.var;
// StringUtils.isNotBlank(msg);
// if (org.apache.commons.lang.StringUtils.isNotBlank(msg)) {
if ( StringUtils.isNotBlank(msg)) {
if ("ping".equals(msg)) {
log.info("get ping");
this.sendMsg("pong");
} else {
try {
log.info(this.userId + ":消息,报文:" + msg);
//解析报文
JSONObject jsonObject = JSON.parseObject(msg);
String msgType = jsonObject.getString("msg");
// if (screenshot.equals(msgType)) {
// onScreenshotMsg(jsonObject);
// } else if (status.equals(msgType)) {
// onStatusChangeMsg(jsonObject);
// }
// screenshotLogRepository.
//追加发送人 范篡改
jsonObject.put("sendUserId", this.userId);
String receiveUserId = jsonObject.getString("receiveUserId");
//存在receiveUserId 单发
// org.dom4j.util.StringUtils.
// org.apache.commons.lang.StringUtils.isNotBlank()
// ReturnT success = ReturnT.success(jsonObject);
JSONObject success = ReturnT.success(jsonObject);
String stringRes = JsonUtil.objectToString(success);
log.info("stringRes {}", stringRes);
// StringUtils.isNotBlank()
// if (org.apache.commons.lang.StringUtils.isNotBlank(receiveUserId)) {
if ( StringUtils.isNotBlank(receiveUserId)) {
log.info("单发 receiveUserId {}", receiveUserId);
if (webSocketMap.containsKey(receiveUserId)) {
String res = jsonObject.toJSONString();
log.info("res {}", res);
// ReturnT success = ReturnT.success(jsonObject);
// String string = JsonUtil.objectToString(success);
log.info("string {}", stringRes);
// webSocketMap.get(receiveUserId).sendMsg(jsonObject.toJSONString());
// webSocketMap.get(receiveUserId).sendMsg(res);
webSocketMap.get(receiveUserId).sendMsg(stringRes);
}
} else {//不存在 则群发
log.info("不存在 则群发");
webSocketMap.forEach((k, v) -> {
// v.sendMsg(msg);
v.sendMsg(stringRes);
});
}
} catch (Exception e) {
e.printStackTrace();
this.sendMsg("pong");
}
}
}
}
/**
* 自定义推送消息
*
* @param msg 消息内容
* @param userId 用户id
* @return: java.lang.Boolean
* @author: pansong
* @date: 2020/6/11 23:49
**/
public static Boolean sendInfo(String msg, String userId) throws IOException {
boolean notBlank = StringUtils.isNotBlank(userId);
// if (org.apache.commons.lang.StringUtils.isNotBlank(userId)
if (notBlank
&& webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).sendMsg(msg);
log.info(userId + " : 发送,报文:" + msg);
return true;
} else {
log.error(userId + " : 掉线");
return false;
}
}
public static Boolean 群发(String msg) throws IOException {
webSocketMap.forEach((k, v) -> {
// v.sendMsg(msg);
v.sendMsg(msg);
});
return true;
}
public static Boolean massSend(String msg) throws IOException {
webSocketMap.forEach((k, v) -> {
// v.sendMsg(msg);
v.sendMsg(msg);
});
return true;
}
}
<template>
<div class="app-container">
<el-form
:model="queryParams"
ref="queryForm"
size="small"
label-width="100px"
>
<el-form-item label="类型" prop="type">
<el-select
v-model="queryParams.type"
clearable
placeholder="请选择类型"
>
<el-option value="1" label="全服执行SQL"></el-option>
<el-option value="2" label="查看日志"></el-option>
</el-select>
</el-form-item>
<el-form-item label="SQL语句">
<el-input
type="textarea"
:rows="3"
v-model="queryParams.msg"
placeholder="请输入SQL语句"
clearable
/>
</el-form-item>
<el-form-item>
<el-button
type="primary"
icon="el-icon-search"
size="mini"
@click="submit"
>提 交</el-button
>
</el-form-item>
</el-form>
<el-button type="" @click="init">initWs</el-button>
</div>
</template>
<script>
// import { getToken } from "@/utils/auth";
import common from "@/utils/common";
export default {
data() {
common. backendIpPort ='localhost:8003'
return {
// 此处为websocket地址, 8080是springboot监听的web端口
path: `ws://${common. backendIpPort}/webSocket/1`,
socket: "",
loading: false,
queryParams: {},
};
},
mounted() {
this.init();
},
methods: {
initWs(){
this.init()
},
init: function () {
if (typeof WebSocket === "undefined") {
console.log("浏览器不支持websocket");
} else {
//涉及到spring security鉴权,此处加上token (正常的http请求可以设置请求头,
// websocket无法设置,只好把token放在Sec-WebSocket-Protocol中)
// let token = getToken();
// this.socket = new WebSocket(this.path, [token]);
this.socket = new WebSocket(this.path);
this.socket.onopen = this.open;
this.socket.onerror = this.error;
this.socket.onmessage = this.getMessage;
}
},
open: function () {
console.log("websocket连接成功");
},
error: function (error) {
console.log("websocket连接错误", error);
},
getMessage: function (msg) {
console.log("收到消息,", msg);
},
send: function (params) {
this.socket.send(params);
},
close: function (e) {
console.log("websocket连接关闭");
},
submit: function () {
this.loading = true;
let params = JSON.stringify(this.queryParams);
this.send(params);
console.log("发送消息,", params);
this.loading = false;
},
},
destroyed() {
this.socket.onclose = this.close;
},
};
</script>
我把spring-boot-starter-web 默认的 spring-boot-starter-tomcat exclusion, 然后再导入 好像就可以了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- springboot tomcat 支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
文档:我把spring-boot-starter-web 默认的 s…
链接:http://note.youdao.com/noteshare?id=f78c7f25a5c0ce2a3c78d5c4a9c8af27&sub=2738E9FBE202426B881F07981BE8682D
添加链接描述