From 07888aafd27ce3ebce9c541819b8d74f01c422a8 Mon Sep 17 00:00:00 2001 From: Elrabu <busch.elias@web.de> Date: Sun, 18 Feb 2024 20:46:01 +0100 Subject: [PATCH] eb093: update: fixed server.java, added Tests --- .../battlearena/Model/Multiplayer/Server.java | 20 +++++++--- .../Model/Multiplayer/ServerTest.java | 37 +++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) create mode 100644 src/test/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/ServerTest.java diff --git a/src/main/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/Server.java b/src/main/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/Server.java index 19c96a42..8b49dfb6 100644 --- a/src/main/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/Server.java +++ b/src/main/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/Server.java @@ -46,16 +46,26 @@ public class Server { public void startServer() throws IOException { Server server = new Server(); log.info("server starting..."); - server.start(ipaddress,4444); + server.start(4444); } - public void start(String host_ip, int port) throws IOException { + public void start(int port) throws IOException { serverSocket = new ServerSocket(port); log.info("server started!"); started = true; - while (true){ - new ServerHandler(serverSocket.accept()).start(); - } + + log.info("server accepting Thread starting..."); + Thread serverThread = new Thread(() -> { + while (true) { + try { + new ServerHandler(serverSocket.accept()).start(); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + serverThread.start(); + log.info("requests accepting Thread started!"); } private static class ServerHandler extends Thread { diff --git a/src/test/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/ServerTest.java b/src/test/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/ServerTest.java new file mode 100644 index 00000000..227f1b25 --- /dev/null +++ b/src/test/java/de/hdm_stuttgart/battlearena/Model/Multiplayer/ServerTest.java @@ -0,0 +1,37 @@ +package de.hdm_stuttgart.battlearena.Model.Multiplayer; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.ServerSocket; + +import static org.junit.jupiter.api.Assertions.*; + +class ServerTest { + + private static String ipaddress = "localhost"; + private ServerSocket serverSocket; + private int port = 4444; + private boolean started = false; + + @Test + void startServer() throws IOException { + Server server = new Server(); + server.start(port); + assertTrue(server.isStarted()); + } + + @Test + void stopServer() { + + try { + //start Server somehow so that serverSocket is not null + + serverSocket.close(); // Close the server socket to break out of accept() in the main thread + started = false; + assertFalse(started); + } catch (IOException e) { + + } + } +} \ No newline at end of file -- GitLab