创建配置类
package com.example.emos.api.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket配置
*
* @author jl
* @since 2021/1/19 22:05
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.example.emos.api.websocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author jl
* @since 2021/1/19 22:05
*/
@Component
@ServerEndpoint("/webSocket/{key}")
@Slf4j
public class WebSocket {
private Session session;
private static final ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam(value = "key") String key) {
this.session = session;
webSocketMap.put(key, this);
log.info("【websocket消息】有新的连接【{}】, 总数:{}", key, webSocketMap.size());
}
@OnClose
public void onClose(@PathParam(value = "key") String key) {
webSocketMap.remove(key);
log.info("【websocket消息】连接断开, 总数:{}", webSocketMap.size());
}
@OnMessage
public void onMessage(String message, @PathParam(value = "key") String key) {
log.info("【websocket消息】收到客户端【{}】发来的消息:{}", key, message);
}
/**
* 指定用户发送
*/
public void sendMessage(String message, String key) {
log.info("【websocket消息】发送指定消息, message={}, key={}", message, key);
try {
webSocketMap.get(key).session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 群发
*/
public void sendMessage(String message) {
log.info("【websocket消息】广播消息, message={}", message);
for (String key : webSocketMap.keySet()) {
try {
webSocketMap.get(key).session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
使用
// websocket向前端页面推送付款结果
webSocket.sendMessage("付款成功", token);
前端代码
package.json
{
"name": "emos-vue",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"dayjs": "1.10.4",
"echarts": "5.1.1",
"element-plus": "1.0.2-beta.42",
"jquery": "3.6.0",
"jspdf": "2.3.1",
"screenfull": "5.1.0",
"tim-upload-plugin": "1.0.1",
"trtc-js-sdk": "4.10.2",
"vue": "3.0.3",
"vue-native-websocket-vue3": "3.1.0",
"vue3-cookies": "1.0.1"
},
"devDependencies": {
"@vitejs/plugin-vue": "1.2.1",
"@vue/compiler-sfc": "3.0.11",
"less": "4.1.1",
"less-loader": "8.0.0",
"sass": "1.32.8",
"sass-loader": "11.0.1",
"vite": "2.1.5",
"vite-plugin-svg-icons": "0.4.1",
"vue-router": "4.0.5"
}
}
main.js
//导入Cookie库,可以读写Cookie数据
import VueCookies from 'vue3-cookies'
app.use(VueCookies); //挂载Cookie插件
//使用WebSocket,后端项目给前端页面推送通知更
import VueNativeSock from "vue-native-websocket-vue3";
app.use(VueNativeSock,"ws://192.168.50.182:8090/emos-api/webSocket/" + app.config.globalProperties.$cookies.get('token'), {"format": "json"} // 向后台传输json格式数据
);
使用
created() {
let that = this;
that.routeHandle(that.$route);
that.$options.sockets.onopen = function(resp) {
//发送心跳检测,避免超时后服务端切断连接
setInterval(function() {
that.$socket.sendObj({ opt: 'ping' });
}, 60 * 1000);
};
},
methods: {
init: function(id) {
let that = this;
that.visible = true;
that.dataForm.id = id;
that.result = false;
that.qrCode = null;
that.$nextTick(() => {
// 获取token
let token = that.$cookies.get('token');
that.$options.sockets.onmessage = function(resp) {
let data = resp.data;
if (data == '付款成功') {
that.$emit('refreshDataList');
that.result = true;
}
};
that.$http('amect/createNativeAmectPayOrder', 'POST', { amectId: id }, true, function(resp) {
that.qrCode = resp.qrCodeBase64;
});
});
},
cancelHandle:function(){
this.visible=false
},
closeHandle:function(){
this.visible = false
this.$emit('refresh');
},
successHandle:function(){
let that=this
that.$http("amect/searchNativeAmectPayResult","POST",{amectId:that.dataForm.id},true,function(resp){
that.$emit('refreshDataList');
that.visible = false
})
}
}