系统在线用户统计
简单说下项目概况,SpringBoot+vue,前后端分离。
需求是,home页面实时显示系统在线人数,根据session和请求ip地址判断用户数量,使用Websocket实现前后端广播,通信。
后端代码如下
pom文件,配置文件,代码(如果打war包在tomcat部署,配置文件注释掉)
<dependency>
<!-- websocket -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
//@Configuration
//@EnableWebSocket
public class WebConfigurers implements WebSocketConfigurer {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
}
}
/**
* 用来存放每个客户端对应的WebSocket对象
*/
private static CopyOnWriteArraySet<WebsocketServer> webSocketSet = new CopyOnWriteArraySet<>();
private static Logger log = LoggerFactory.getLogger(WebsocketServer.class);
private Session session;
private String ipAddress;
private static int onlineCount = 0;
@OnOpen
public void onOpen(Session session) {
this.session = session;
String hostAddress = WebsocketUtil.getRemoteAddress(session).getAddress().getHostAddress();
log.info("客户端IP:" + hostAddress);
log.info("来自"+session.getId()+"的连接.......");
this.ipAddress = hostAddress;
log.info("客户端IP:" + this.ipAddress);
webSocketSet.add(this);
}
@OnClose
public void onClose(Session session, @PathParam("key") String classKey) throws IOException {
//删除
webSocketSet.remove(this);
getOnlineCount();
log.info("当前在线人数:" + onlineCount);
sendAll(String.valueOf(onlineCount));
log.info("有一连接关闭");
}
@OnMessage
public void onMessage(Session session, String key) throws IOException {
getOnlineCount();
sendAll(String.valueOf(onlineCount));
}
public void sendAll(String message) throws IOException {
log.info("发给所有人!");
//遍历
for (WebsocketServer websocketServer: webSocketSet){
sendMessage(websocketServer,String.valueOf(onlineCount));
}
}
public void sendMessage(WebsocketServer websocketServer, String message) throws IOException{
websocketServer.session.getAsyncRemote().sendText(message);
}
@OnError
public void onError(Session session, Throwable error, @PathParam("key") String classKey) {
error.printStackTrace();
log.info("出错啦");
}
private static synchronized Integer getOnlineCount(){
onlineCount = webSocketSet.size();
return onlineCount;
}
前端代码截一部分(前端基本不变,可在网上找到)
function initWebSocket(url) {
if ("WebSocket" in window) {
webSocket = new WebSocket(url);//创建socket对象
console.log(webSocket)
} else {
alert("该浏览器不支持websocket!");
}
//打开
webSocket.onopen = function() {
webSocketOpen();
};
//收信
webSocket.onmessage = function(e) {
webSocketOnMessage(e);
};
//关闭
webSocket.onclose = function() {
webSocketClose();
};
//连接发生错误的回调方法
webSocket.onerror = function() {
console.log("WebSocket连接发生错误");
};
}
每次系统有新的登录,则全局广播