java代码获取当前页面人数
时间: 2023-09-02 22:08:56 浏览: 63
获取当前页面人数可以通过前端页面的JavaScript来实现。具体实现方法是:
1. 首先在前端页面中加入以下代码:
```javascript
<script>
var onlineNum = 0;
var websocketUrl = 'ws://xxxxxx'; //websocket的url地址(需要实际确定)
var websocket = new WebSocket(websocketUrl);
websocket.onmessage = function(event) {
var message = event.data;
if (message === 'onlineNum') {
websocket.send(JSON.stringify({type: 'onlineNum', data: onlineNum}));
}
};
setInterval(function() {
onlineNum = document.querySelectorAll('.online').length; //获取class为online的元素个数
websocket.send('onlineNum');
}, 1000); //每秒钟发送一次请求获取当前页面人数
</script>
```
2. 接着在服务端代码中使用WebSocket来接收前端发送过来的请求,并发送当前页面人数:
```java
@ServerEndpoint(value = "/websocket")
public class OnlineNumWebSocket {
private static Set<OnlineNumWebSocket> webSocketSet = new HashSet<OnlineNumWebSocket>();
private static int onlineNum = 0;
@OnOpen
public void onOpen(Session session) throws IOException {
webSocketSet.add(this);
// 返回当前页面人数
sendMessage(session, "onlineNum", onlineNum);
}
@OnClose
public void onClose(Session session) {
webSocketSet.remove(this);
}
@OnError
public void onError(Session session, Throwable error) {
webSocketSet.remove(this);
}
@OnMessage
public void onMessage(Session session, String message) {
JSONObject jsonObject = JSON.parseObject(message);
String type = jsonObject.getString("type");
if ("onlineNum".equals(type)) {
try {
sendMessage(session, "onlineNum", onlineNum);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendMessage(Session session, String type, int data) throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", type);
jsonObject.put("data", data);
session.getBasicRemote().sendText(jsonObject.toJSONString());
}
public static synchronized void addOnlineNum() {
onlineNum++;
updateOnlineNum();
}
public static synchronized void subOnlineNum() {
onlineNum--;
updateOnlineNum();
}
private static void updateOnlineNum() {
for (OnlineNumWebSocket webSocket : webSocketSet) {
try {
webSocket.sendMessage(webSocket.getSession(), "onlineNum", onlineNum);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
最后,就可以通过WebSocket获取到前端页面的在线人数了。