Prechádzať zdrojové kódy

No more System.exit()

Maven Surefire doesn't allow System.exit() to be called. Now the server
stops all running threads to stop itself.
Tankernn 9 rokov pred
rodič
commit
addd5a2a2d

+ 5 - 0
src/main/java/server/LocalClient.java

@@ -15,6 +15,11 @@ public class LocalClient extends Client {
 		readuser.start();
 	}
 	
+	@Override
+	public void disconnect() {
+		readuser.interrupt();
+	}
+	
 	@Override
 	public void send(Object message) {
 		System.out.println(message);

+ 16 - 2
src/main/java/server/Server.java

@@ -9,6 +9,7 @@ import java.net.ServerSocket;
 import java.util.ArrayList;
 import java.util.Properties;
 import java.util.Scanner;
+import java.util.Set;
 
 import common.Message;
 import server.CommandHandler;
@@ -70,7 +71,7 @@ public class Server {
 	}
 
 	static void getClients() {
-		while(true) {
+		while(!so.isClosed()) {
 			Client newClient = null;
 			try {
 				newClient = new Client(Server.so.accept());
@@ -82,6 +83,9 @@ public class Server {
 			} catch (ArrayIndexOutOfBoundsException ex) {
 				newClient.send(new Message("Server full!"));
 				newClient.disconnect(false);
+			} catch (IOException ex) {
+				if (so.isClosed())
+					return;
 			} catch (Exception ex) {
 				System.out.println("Could not get new client!");
 				ex.printStackTrace();
@@ -129,7 +133,17 @@ public class Server {
 		
 		log.close();
 		
-		System.exit(0);
+		OPClient.disconnect();
+		
+		try {
+			so.close();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		
+		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
+		for (Thread th: threadSet)
+			System.out.println(th.toString() + ", " + th.isAlive());
 	}
 	
 	public static int CInt(String str) {

+ 9 - 3
src/test/java/client/ClientTestCase.java

@@ -7,15 +7,21 @@ import org.junit.BeforeClass;
 import org.junit.Test;
 
 import server.Server;
-import server.ServerTestSuite;
 
 public class ClientTestCase {
 	public static ChatWindow user1;
 	public static ChatWindow user2;
-
+	
+	static Thread runServer = new Thread(){
+    	@Override
+    	public void run() {
+    		Server.main(new String[]{});
+    	}
+    };
+	
     @BeforeClass 
     public static void setUpClass() {
-    	ServerTestSuite.runServer.start();
+		runServer.start();
         user1 = new ChatWindow("localhost", 25566, "user1");
         assertTrue(user1.so.isConnected());
     }