1.添加pom依赖
<!-- WebSocket完成订单通知 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.代码
后端
package com.rocketmq.ws;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author liudean
* @date 2022/1/11 14:54
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.rocketmq.ws;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
/**
* @author liudean
* 自定义返回格式
* @date 2022/1/11 14:54
*/
public class ServerEncoder implements Encoder.Text<JSONObject> {
@Override
public String encode(JSONObject jsonObject){
return JSON.toJSONString(jsonObject);
}
@Override
public void init(EndpointConfig endpointConfig) {
}
@Override
public void destroy() {
}
}
package com.rocketmq.ws;
import com.alibaba.fastjson.JSON;
import com.rocketmq.common.ResultMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author liudean
* @date 2022/1/11 14:52
*/
@Component
@ServerEndpoint(value = "/websocket/{uuid}",encoders = ServerEncoder.class)
public class WebSocketServer {
public static ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>();
private final Logger log = LoggerFactory.getLogger("WebSocketServer");
/**
* 连接建立成功调用的方法
* */
@OnOpen
public void onOpen(Session session, @PathParam("uuid") String uuid) {
log.info("客户端:" + uuid + "连接成功了");
clients.put(uuid, session);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("uuid") String uuid) {
log.info("客户端:" + uuid + "断开连接了");
clients.remove(uuid);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("收到客户端消息:"+message);
}
@OnError
public void one rror(Throwable error) {
error.printStackTrace();
}
/**
* 测试
* 实现服务器主动推送
* 之后方法里面可通过建立连接的uuid推送到客户端
*/
public void sendMessage(String uuid) throws IOException, EncodeException {
Session session = WebSocketServer.clients.get(uuid);
if (session != null) {
System.out.println("连接成功,处理返回"+uuid);
session.getBasicRemote().sendObject(JSON.toJSON(ResultMsg.SUCCESS.setNewData("我草,成功了")));
} else {
System.out.println("找不到客户端:"+uuid+"的连接");
}
}
}
前端
<template>
<div>
<el-row>
<el-button type="success" @click="onSubmit">成功按钮</el-button>
</el-row>
</div>
</template>
<script>
export default {
data() {
return {
};
},
mounted() {
},
methods: {
onSubmit() {
let uuid = "8246666666"
this.$axios
.post("/send", {
uuid: uuid,
})
.then((res) => {
console.log(res);
if (res.data.resultCode === 200) {
//建立连接
this.createSocket(uuid);
} else {
alert(1)
}
});
},
createSocket(uuid){
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
let socketUrl = "ws://192.168.3.254:8021/websocket/" + uuid;
if (socket != null) {
socket.close();
socket = null;
}
// 开启一个websocket服务
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
//浏览器端收消息,获得从服务端发送过来的文本消息
socket.onmessage = function(event) {
console.log("返回了");
console.log(event);
var result = $.parseJSON(event.data);
if(result.code === 200){
}else{
layer.msg(result.msg);
}
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("Socket发生了错误");
}
//窗口关闭
$(window).unload(function(event){
socket.close();
});
}
return socket;
}
},
};
</script>