Identity, port, hostname acknowledgement

This commit is contained in:
2024-11-25 16:56:06 +02:00
parent 6bee3a0e13
commit 8713c6e7b3
9 changed files with 74 additions and 25 deletions

View File

@@ -1,34 +1,46 @@
package io.github.lumijiez;
import com.google.gson.Gson;
import io.javalin.Javalin;
import io.javalin.websocket.WsContext;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class JavalinConfig {
private static final Map<String, WsContext> users = new ConcurrentHashMap<>();
private static final Map<String, NodeInfo> registeredNodes = new ConcurrentHashMap<>();
private static final Map<String, WsContext> nodes = new ConcurrentHashMap<>();
private static final Gson gson = new Gson();
public static void setup(Javalin app) {
app.ws("/discovery", ws -> {
ws.onConnect(ctx -> {
String id = ctx.sessionId();
users.put(id, ctx);
broadcast("Discovery-Join", "Join");
});
ws.onConnect(ctx -> {
// ToDo
// A general notification
nodes.put(ctx.sessionId(), ctx);
});
ws.onClose(ctx -> {
String id = ctx.sessionId();
users.remove(id);
broadcast("Discovery-Leave", "Leave");
});
ws.onMessage(ctx -> {
String message = ctx.message();
NodeInfo nodeInfo = gson.fromJson(message, NodeInfo.class);
registeredNodes.put(ctx.sessionId(), nodeInfo);
broadcastNodeCount();
});
ws.onClose(ctx -> {
registeredNodes.remove(ctx.sessionId());
broadcastNodeCount();
});
});
}
private static void broadcast(String sender, String message) {
users.values().forEach(ctx -> ctx.send(users.size()));
private static void broadcastNodeCount() {
List<NodeInfo> nodeInfoList = new ArrayList<>(registeredNodes.values());
String nodesJson = gson.toJson(nodeInfoList);
nodes.values().forEach(ctx -> ctx.send(nodesJson));
}
public record NodeInfo(String hostname, int port) { }
}

View File

@@ -4,7 +4,7 @@
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout>
<Pattern>
%highlight{%d{yyyy-MM-dd HH:mm:ss} %-5level [%t]: %msg}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue}%n
%d{yyyy-MM-dd HH:mm:ss} %highlight{%-5level}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue}: %highlight{%msg}{FATAL=red, ERROR=red}%n
</Pattern>
</PatternLayout>
</Console>