一:实现消息实时通知
实现消息的实时通知有2种方案:即推和拉。拉,就是页面用Ajax去轮询访问后台是否有新的消息但是资源消耗很大,推即服务器通过“长链接”去实时推送消息去前端页面主要的实现就是使用WwbSocket。
这里,我们使用的是springboot2.0.x版本来整合WebScoket。
二:代码
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.配置Config
package com.config.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket配置
*
* @author yueli.liao
* @date 2019-03-12 11:25
*/
@Configuration
public class WebSocketConfig {
/**
* 开启WebSocket功能
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.webSocket服务器
package com.config.websocket.service;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.apache.tomcat.websocket.WsSession;
import org.springframework.stereotype.Component;
import com.config.websocket.model.WsSessionModel;
import lombok.extern.slf4j.Slf4j;
/**
* WebSocket服务入口
*
* @author monxz
* @date 2019-03-12 15:16
*/
@Slf4j
@Component
@ServerEndpoint("/websocket/{id}")
public class WebSocketServer3 {
// 用来存储当前在线的客户端(此map线程安全)
// private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
//
//========================================================================
private static ConcurrentHashMap<String, WsSessionModel> webSocketMap = new ConcurrentHashMap<>();
/**
* 连接建立成功后调用
*/
@OnOpen
public void onOpen(@PathParam(value = "id") String id, Session session) {
webSocketMap.put(id, new WsSessionModel(id, (WsSession)session)); // 加入map中
log.info("客户端" + id + "加入,当前在线数为:" + getOnlineCount());
try {
sendMessage("您已经登录系统",(WsSession)session);
} catch (IOException e) {
log.error("WebSocket IO异常");
}
}
/**
* 连接关闭时调用
*/
@OnClose
public void onClose() {
webSocketMap.remove(this); // 从map中删除
log.info("有一连接关闭,当前在线数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用
*
* @param message 客户端发送过来的消息<br/>
* 消息格式:内容 - 表示群发,内容|X - 表示发给id为X的客户端
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:" + message);
String[] messages = message.split("[|]");
try {
if (messages.length > 1) {
sendToUser(messages[0], messages[1]);
} else {
sendToAll(messages[0]);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 发生错误时回调
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("WebSocket发生错误");
error.printStackTrace();
}
/**
* 推送信息给指定ID客户端,如客户端不在线,则返回不在线信息给自己
*
* @param message 客户端发来的消息
* @param sendClientId 客户端ID
* @throws IOException
*/
public void sendToUser(String message, String sendClientId) throws IOException {
WsSessionModel model=webSocketMap.get(sendClientId);
sendMessage(message, model.getSession());
}
/**
* 推送发送信息给所有人
*
* @param message 要推送的消息
* @throws IOException
*/
public void sendToAll(String message) throws IOException {
for (String key : webSocketMap.keySet()) {
sendMessage(message, webSocketMap.get(key).getSession());
}
}
/**
* 推送消息
*
* @param message 要推送的消息
* @throws IOException
*/
private void sendMessage(String message,WsSession session) throws IOException {
session.getBasicRemote().sendText(message);
}
private static synchronized int getOnlineCount() {
return webSocketMap.keySet().size();
}
}
4.页面配置
//=================初始化webseocket
function initWebsocket(id){
var websocket = null;
// 判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
// 为了方便测试,故将链接写死
websocket = new WebSocket("ws://localhost:8987/websocket/"+id);
} else{
alert('Not support websocket')
}
// 连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("发生错误");
};
// 连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("打开连接");
}
// 接收到消息的回调方法
websocket.onmessage = function(event){
initMyNotic();
toastr.info(event.data)
// setMessageInnerHTML(event.data);
}
// 连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("关闭连接");
}
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常
window.onbeforeunload = function(){
websocket.close();
}
}
三:流程说明
1.流程图
2.代码说明
在服务器端,实则是通过一个id来存储一个session的Map,然后通过Session.sendText()来发送信息的。