一、前端代码
1. websocket.js
/**
* 参数说明:
* webSocketURL:String webSocket服务地址 eg: ws://127.0.0.1:8088/websocket (后端接口若为restful风格可以带参数)
* callback:为带一个参数的回调函数
* message:String 要传递的参数值(不是一个必要的参数)
*/
export default {
// 初始化webSocket
webSocketInit (webSocketURL) { // ws://127.0.0.1:8088/websocket
this.webSocket = new WebSocket(webSocketURL)
this.webSocket.onopen = this.onOpenwellback
this.webSocket.onmessage = this.onMessageCallback
this.webSocket.onerror = this.onErrorCallback
this.webSocket.onclose = this.onCloseCallback
},
// 自定义回调函数
setOpenCallback (callback) { // 与服务端连接打开回调函数
this.webSocket.onopen = callback
},
setMessageCallback (callback) { // 与服务端发送消息回调函数
this.webSocket.onmessage = callback
},
setErrorCallback (callback) { // 与服务端连接异常回调函数
this.webSocket.onerror = callback
},
setCloseCallback (callback) { // 与服务端连接关闭回调函数
this.webSocket.onclose = callback
},
close () { // 关闭连接
this.webSocket.close()
},
sendMessage (message) { // 发送消息函数
this.webSocket.send(message)
}
}
2. 接收消息的页面
<template>
<div>
<el-button type="primary" @click="sendMessage">发送消息</el-button>
<span>{{ text }}</span>
</div>
</template>
<script>
import webSocket from '@/api/websocket'
export default {
name: 'WebSocketTest',
data () {
return {
text: null,
webSocketObject: null
}
},
created () {
// webSocket.webSocketInit(process.env.VUE_APP_BASE_API.replace("http","ws")+"/evgis/todoStatus")
webSocket.webSocketInit('ws://127.0.0.1:8080/websocket') // 初始化webSocket
// 按需进行绑定回调函数
webSocket.setOpenCallback(res => {
console.log('连接建立成功', res)
})
webSocket.setMessageCallback(res => {
this.text = res.data
// 在此处进行数据刷新操作即可实现数据发生改变时实时更新数据
console.log('接收到回信', res)
})
webSocket.setErrorCallback(res => {
console.log('连接异常', res)
})
webSocket.setCloseCallback(res => {
console.log('连接关闭', res)
})
},
methods: {
sendMessage () {
// 数据发生改变时给WebSocket发送消息,让其进行广播操作
webSocket.sendMessage()
}
}
}
</script>
<style>
</style>
二、后端代码
1. 导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 创建websocket类
@Component
@Slf4j
@ServerEndpoint("/websocket") //暴露的ws应用的路径
public class WebSocket {
// 用来存储服务连接对象
private static Map<String ,Session> clientMap = new ConcurrentHashMap<>();
/**
* 客户端与服务端连接成功
* @param session
*/
@OnOpen
public void onOpen(Session session){
/*
do something for onOpen
与当前客户端连接成功时
*/
clientMap.put(session.getId(),session);
}
/**
* 客户端与服务端连接关闭
* @param session
*/
@OnClose
public void onClose(Session session){
/*
do something for onClose
与当前客户端连接关闭时
*/
clientMap.remove(session.getId());
}
/**
* 客户端与服务端连接异常
* @param error
* @param session
*/
@OnError
public void onError(Throwable error,Session session) {
error.printStackTrace();
}
/**
* 客户端向服务端发送消息
* @param message
* @throws IOException
*/
@OnMessage
public void onMsg(Session session,String message) throws IOException {
/*
do something for onMessage
收到来自当前客户端的消息时
*/
sendAllMessage(message);
}
//向所有客户端发送消息(广播)
private void sendAllMessage(String message){
Set<String> sessionIdSet = clientMap.keySet(); //获得Map的Key的集合
// 此处相当于一个广播操作
for (String sessionId : sessionIdSet) { //迭代Key集合
Session session = clientMap.get(sessionId); //根据Key得到value
session.getAsyncRemote().sendText(message); //发送消息给客户端
}
}
}
3.创建WebSocketConfig配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
4. 接口测试群发消息
@Autowired
private WebSocket webSocket;
// http://127.0.0.1:8080/hello?name=lisi
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestParam(name = "msg") String msg) throws IOException {
webSocket.onMsg(null,msg);
return msg;
}
ps:以上代码初步的实现了后端推送实时消息到页面的功能,但还有很多需要优化的地方。持续更新中。