commit 16/06/2025

This commit is contained in:
2025-06-17 16:23:50 +07:00
parent f2bb3500c9
commit c617157a0b
33 changed files with 321 additions and 56 deletions

74
src/web/WebServer.java Normal file
View File

@@ -0,0 +1,74 @@
package web;
import io.javalin.Javalin;
import lombok.Getter;
import org.tinylog.Logger;
public class WebServer {
private Javalin app;
private @Getter boolean isRunning = false;
/**
* Start the web server on the specified port.
* @param listenport the port to listen on
*/
public void Start(int listenport){
isRunning = false;
app = null;
try{
var xx = Javalin.create(config -> {
config.useVirtualThreads = true;
config.staticFiles.add("/html");
}).start(listenport);
isRunning = true;
app = xx;
Logger.info("Web server started on port {}", listenport);
AssignRoutes();
} catch (Exception e){
Logger.error("Failed to start web server: {}", e.getMessage());
}
}
private void AssignRoutes(){
if (app == null) {
Logger.error("Web server is not running, cannot assign routes.");
return;
}
app.ws("/ws", ws->{
ws.onConnect(ctx -> {
Logger.info("WebSocket connected: {}", ctx.session.getRemoteAddress());
});
ws.onMessage(ctx -> {
Logger.info("WebSocket message received: {}", ctx.message());
// Handle incoming messages here
});
ws.onClose(ctx -> {
Logger.info("WebSocket closed: {} ", ctx.session.getRemoteAddress());
});
ws.onError(ctx -> {
Logger.error("WebSocket error: {}", ctx.error().getMessage());
});
});
}
/**
* Stop the web server if it is running.
*/
public void Stop(){
if (app!=null){
try{
app.stop();
} catch (Exception e){
Logger.error("Failed to stop web server: {}", e.getMessage());
}
app = null;
}
isRunning = false;
}
}