feat: adding all ping pong function

This commit is contained in:
wzp 2024-12-17 11:43:30 +08:00
parent daa7a814f6
commit 2f3f5806c3

View File

@ -21,6 +21,7 @@ import org.mmga.clubs.service.UserService;
import org.mmga.clubs.utils.JwtUtils;
import org.mmga.clubs.utils.WebSocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
@ -38,6 +39,7 @@ public class ChessController {
private static final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, User> users = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<UUID, Room> rooms = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Session, Boolean> pingPong = new ConcurrentHashMap<>();
private static JwtUtils jwtUtils;
private static UserService userService;
@ -80,9 +82,6 @@ public class ChessController {
users.put(sessionId, user);
sessions.put(sessionId, session);
isLogin = true;
for (String s : messageQueue) {
this.onMessage(s, session);
}
if (existsUser != null) {
users.remove(existsUser);
Room roomByPlayer = getRoomByPlayer(existsUser);
@ -94,19 +93,19 @@ public class ChessController {
Session remove = sessions.remove(existsUser);
remove.close();
}
ByteBuf buffer = Unpooled.buffer();
buffer.writeLong(System.currentTimeMillis());
session.getAsyncRemote().sendPing(buffer.nioBuffer());
for (String s : messageQueue) {
this.onMessage(s, session);
}
}
@OnMessage
public void onPong(PongMessage pongMessage, Session session) {
System.out.println(pongMessage);
ByteBuffer applicationData = pongMessage.getApplicationData();
ByteBuf byteBuf = Unpooled.copiedBuffer(applicationData);
long l = byteBuf.readLong();
System.out.println(l);
long l = System.currentTimeMillis() - byteBuf.readLong();
log.info("client sent pong response, latency is {}ms", l);
pingPong.put(session, true);
}
@OnMessage
@ -217,4 +216,18 @@ public class ChessController {
sessions.remove(sessionId);
users.remove(sessionId);
}
@SneakyThrows
@Scheduled(fixedDelay = 10000)
public static void connectionManager() {
for (Session value : sessions.values()) {
if (!pingPong.getOrDefault(value, true)) {
value.close();
continue;
}
pingPong.put(value, false);
log.info("send ping to session {}", value.getId());
value.getAsyncRemote().sendPing(Unpooled.buffer().writeLong(System.currentTimeMillis()).nioBuffer());
}
}
}