整合WebSocket实现简单的消息推送功能
Websocket两种简单实现:
实现方式一:
引入Maven依赖:
<!--websocket 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
后端代码实现:
- 新建一个WebSocket的配置类,用来开启WebSocket的支持
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@ConditionalOnWebApplication
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 新建一个客户端实体类WebSocketClient用来存储连接的Session和Uri
import javax.websocket.Session;
public class WebSocketClient {
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//连接的uri
private String uri;
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
- 新建WebSocketService,用来创建和处理连接
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint(value = "/websocket/{userName}")
@Component
public class WebSocketService {
private static final Logger log = LoggerFactory.getLogger(WebSocketService.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
private static ConcurrentHashMap<String, WebSocketClient> webSocketMap = new ConcurrentHashMap<>();
/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
private Session session;
/**接收userName*/
private String userName="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session, @PathParam("userName") String userName) {
if(!webSocketMap.containsKey(userName))
{
addOnlineCount(); // 在线数 +1
}
this.session = session;
this.userName= userName;
WebSocketClient client = new WebSocketClient();
client.setSession(session);
client.setUri(session.getRequestURI().toString());
webSocketMap.put(userName, client);
log.info("----------------------------------------------------------------------------");
log.info("用户连接:"+userName+",当前在线人数为:" + getOnlineCount());
try {
sendMessage("来自后台的反馈:连接成功");
} catch (IOException e) {
log.error("用户:"+userName+",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if(webSocketMap.containsKey(userName)){
webSocketMap.remove(userName);
if(webSocketMap.size()>0)
{
//从set中删除
subOnlineCount();
}
}
log.info("----------------------------------------------------------------------------");
log.info(userName+"用户退出,当前在线人数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到用户消息:"+userName+",报文:"+message);
//可以群发消息
//消息保存到数据库、redis
if(StringUtils.hasText(message)){
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:"+this.userName+",原因:"+error.getMessage());
error.printStackTrace();
}
/**
* 连接服务器成功后主动推送
*/
public void sendMessage(String message) throws IOException {
synchronized (session){
this.session.getBasicRemote().sendText(message);
}
}
/**
* 群发消息
* @param userName
* @param message
*/
public static void sendToUser(List<String> persons, String message) {
persons.forEach(userName-> {
try {
sendMessage(userName, message);
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* 向指定客户端发送消息
* @param userName
* @param message
*/
public static void sendMessage(String userName,String message){
try {
WebSocketClient webSocketClient = webSocketMap.get(userName);
if(webSocketClient!=null){
webSocketClient.getSession().getBasicRemote().sendText(message);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketService.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketService.onlineCount--;
}
public static void setOnlineCount(int onlineCount) {
WebSocketService.onlineCount = onlineCount;
}
public static ConcurrentHashMap<String, WebSocketClient> getWebSocketMap() {
return webSocketMap;
}
public static void setWebSocketMap(ConcurrentHashMap<String, WebSocketClient> webSocketMap) {
WebSocketService.webSocketMap = webSocketMap;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
- 新建一个Controller接口用来测试消息的推送
import com.wang.config.WebSocketService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/websocket")
public class WebSocketController {
@GetMapping("/pushone")
public void pushone()
{
WebSocketService.sendMessage("developer","Hello World!!");
}
}
注意:
正常开发的项目中需要将ws的url和接口的url放开权限认证
Vue项目集成
- 在components中新建WebSocket组件
<template>
<el-button @click="sendDataToServer">给后台发送消息</el-button>
</template>
<script>
export default {
name: 'WebSocket',
data() {
return {
// ws是否启动
wsIsRun: false,
// 定义ws对象
webSocket: null,
// ws请求链接(类似于ws后台地址)
ws: '',
// ws定时器
wsTimer: null
}
},
async mounted() {
this.wsIsRun = true
this.wsInit()
},
methods: {
/**
* 由点击事件触发,发送消息给后端对应onMessage()方法
*/
sendDataToServer() {
if (this.webSocket.readyState === 1) {
this.webSocket.send('来自前端的数据')
} else {
throw Error('服务未连接')
}
},
/**
* 初始化ws
*/
wsInit() {
const wsuri = 'ws://172.16.10.132:8123/websocket/ceshi'
this.ws = wsuri
if (!this.wsIsRun) return
// 销毁ws
this.wsDestroy()
// 初始化ws
this.webSocket = new WebSocket(this.ws)
// ws连接建立时触发
this.webSocket.addEventListener('open', this.wsOpenHanler)
// ws服务端给客户端推送消息
this.webSocket.addEventListener('message', this.wsMessageHanler)
// ws通信发生错误时触发
this.webSocket.addEventListener('error', this.wsErrorHanler)
// ws关闭时触发
this.webSocket.addEventListener('close', this.wsCloseHanler)
// 检查ws连接状态,readyState值为0表示尚未连接,1表示建立连接,2正在关闭连接,3已经关闭或无法打开
clearInterval(this.wsTimer)
this.wsTimer = setInterval(() => {
if (this.webSocket.readyState === 1) {
clearInterval(this.wsTimer)
} else {
console.log('ws建立连接失败')
this.wsInit()
}
}, 3000)
},
wsOpenHanler(event) {
console.log('ws建立连接成功')
},
wsMessageHanler(e) {
console.log('wsMessageHanler')
console.log(e)
// const redata = JSON.parse(e.data)
// console.log(redata)
},
/**
* ws通信发生错误
*/
wsErrorHanler(event) {
console.log(event, '通信发生错误')
this.wsInit()
},
/**
* ws关闭
*/
wsCloseHanler(event) {
console.log(event, 'ws关闭')
this.wsInit()
},
/**
* 销毁ws,断开连接
*/
wsDestroy() {
if (this.webSocket !== null) {
this.webSocket.removeEventListener('open', this.wsOpenHanler)
this.webSocket.removeEventListener('message', this.wsMessageHanler)
this.webSocket.removeEventListener('error', this.wsErrorHanler)
this.webSocket.removeEventListener('close', this.wsCloseHanler)
this.webSocket.close()
this.webSocket = null
clearInterval(this.wsTimer)
}
}
}
}
</script>
<style scoped>
</style>
- 在首页中引用该组件
<template>
<div class="app-container home">
<el-row :gutter="20">
websocket推送
<WebSocket></WebSocket>
</el-row>
<el-divider />
</div>
</template>
import WebSocket from '@/components/WebSocket/WebSocket'
export default {
name: "index",
components: {
WebSocket
},
postman测试
实现方式二:
引入Maven依赖:
<!--websocket 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
后端代码实现:
- 新建一个WebSocket的配置类,用来开启WebSocket的支持
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import javax.annotation.Resource;
@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {
@Resource
private WebSocketHandler defaultHandler;
@Resource
private HandshakeInterceptor defaultInterceptor;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(defaultHandler, "/ws") // api 对应controller
.addInterceptors(defaultInterceptor) // 拦截器
.setAllowedOrigins("*");
}
}
- 新建Websocket拦截器
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;
@Component
public class DefaultInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
// return true 连接成功
// return false 连接失败
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
- 新建Websocket 消息处理类,主要用于建立连接,消息推送
package com.wang.config;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @title
* @description websocket 消息处理类,类似于controller
* @author wzy
* @updateTime 2022/5/24 13:16
* @throws
*/
@Component
public class DefaultHandler implements WebSocketHandler {
Map<String, WebSocketSession> conns = new HashMap<>();
/**
* 建立连接
*
* @param session 会话
* @throws Exception 异常
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 缓存用户信息: userInfo
session.getLocalAddress(); // 获取本地IP
session.getUri();
session.getAttributes();
session.getPrincipal();
session.getAcceptedProtocol();
session.getId();
conns.put(session.getId(), session);
}
/**
* 收到客户端消息后调用的方法
*
* @param session 会话
* @param message 消息
* @throws Exception 异常
*/
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// 接收消息
conns.forEach((k, v) -> {
try {
v.sendMessage(new TextMessage(session.getId() + "说:" + message.getPayload().toString()));
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* 发生错误
*
* @param session 会话
* @param throwable throwable
* @throws Exception 异常
*/
@Override
public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
// 清除用户缓存信息
}
/**
* 关闭连接
*
* @param session 会话
* @param closeStatus 关闭状态
* @throws Exception 异常
*/
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
// 清除用户缓存信息
}
/**
* 是否支持发送部分消息
*
* @return true/false
*/
@Override
public boolean supportsPartialMessages() {
return false;
}
/**
* 自定义发送消息
*
* @param message 消息
* @param username 用户名
*/
public void sendMessage(String message, String username) {
}
}