[TOC]
一、简介
在web通信中,通常会使用Http或异步Ajax实现后台数据同步和消息同步,模式通常为客户端主动查询,服务端被动响应,如果追求消息的及时性和效率,建议采用webSocket通信,这样降低网络请求的时间损耗,目前网上实现webSocket通常是通过Netty或者webSocket依赖实现后端应答,前端本身主流浏览器支持webSocket调用, 主要实现了服务器端推送消息给客户端 项目地址
二、技术要点
- SpringBoot
- spring-boot-starter-websocket
- webSocket
三、实现细节
1.引入核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.创建WebSocket的配置类
/**
* 用于扫描和注册所有携带ServerEndpoint 注解的实例
* @author zhangyongliang
* @create 2019-04-10 17:27
**/
@Configuration
public class WebSocketConfig {
/**
* 用于扫描和注册所有携带ServerEndPoint注解的实例。
* <p>
* PS:若部署到外部容器 则无需提供此类。
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.创建服务端实现类
@Component
@Slf4j
@ServerEndpoint("/messageSocket/{taskUid}/{applyId}")
public class WebSocketServer {
//全部在线会话 PS: 基于场景考虑 这里使用线程安全的Map存储会话对象。
private static Map<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的
private static int onlineCount = 0;
//接收userId
private String userId = "";
/**
* 当客户端打开连接:1.添加会话对象 2.更新在线人数
*/
@OnOpen
public void onOpen(Session session, @PathParam("taskUid") String userId, @PathParam("applyId") String applyId) {
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//加入set中
webSocketMap.put(userId, this);
} else {
webSocketMap.put(userId, this);
//在线数加1
addOnlineCount();
}
log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
try {
String conResult=" "; //需要再连接建立后发送给客户端的消息
sendMessage(conResult);
} catch (Exception e) {
log.error("用户:" + userId + ",网络异常!!!!!!");
}
}
/**
* 收到客户端消息后调用的方法
*/
@OnMessage
public void onMessage(Session session, String message) {
log.info("用户消息:" + userId + ",报文:" + message);
//可以群发消息
//消息保存到数据库、redis
if (StrUtil.isNotBlank(message)) {
try {
//解析发送的报文
JSONObject msgJson = JSONUtil.parseObj(message);
//追加发送人(防止串改)
msgJson.put("fromUserId", this.userId);
String toUserId = msgJson.getStr("toUserId");
//传送给对应toUserId用户的websocket
if (StrUtil.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(msgJson.toString());
} else {
log.error("请求的userId:" + toUserId + "不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 当关闭连接:1.移除会话对象 2.更新在线人数
*/
@OnClose
public void onClose(Session session) {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//从set中删除
subOnlineCount();
}
log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 发送自定义消息
*/
public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
log.info("发送消息到:" + userId + ",报文:" + message);
if (StrUtil.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).sendMessage(message);
} else {
log.error("用户" + userId + ",不在线!");
}
}
/**
* 公共方法:发送信息给所有人
*/
private static void sendMessageToAll(String msg) {
webSocketMap.forEach((id, webSocketServer) -> {
try {
webSocketServer.session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
});
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
4.前端连接
function openSocket() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
layer.msg("您的浏览器不支持WebSocket", {icon: 2});
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
if (socket != null) {
socket.close();
socket = null;
}
//socketUrl可以从后台获取到,便于服务器部署正确连接到服务器地址
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function () {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
console.log('获得服务端发送来的消息:');
//发现消息进入 开始处理前端触发逻辑
var fileResult = JSON.parse(msg.data);
//获取服务端推送的消息,然后进行页面数据更新
//xxxxx业务处理
};
//关闭事件
socket.onclose = function () {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function () {
console.log("websocket发生了错误");
}
}
}
/**
* 通过WebSocket对象发送消息给服务端
*/
function sendMsgToServer() {
var $message = $('#msg');
if ($message.val()) {
webSocket.send(JSON.stringify({username: $('#username').text(), msg: $message.val()}));
$message.val(null);
}
}